MUI DatePicker 无法与 Formik 一起正常工作
我在 React 项目中使用 Formik 来处理表单并使用 MUI UI 组件。
我可以选择日期、月份,但年份部分不会改变。如果我在文本字段中手动输入年份,年份部分不会反映在更改的状态中。
这是我的代码:
<LocalizationProvider dateAdapter={DateAdapter}>
<DatePicker
name="birthday"
id="birthday"
variant="standard"
label="Birthday"
value={formik.values.birthday}
renderInput={(params) => (
<TextField {...params} variant="standard" fullWidth/>
)}
onChange={(value) => formik.setFieldValue('birthday', value, true)}
error={formik.touched.birthday && Boolean(formik.errors.birthday)}
helperText={formik.touched.birthday && formik.errors.birthday}
/>
</LocalizationProvider>
初始状态:
const initialFormState = {
birthday: Date.now(),
};
所有其他组件都正常工作并且状态更改立即显示。
I am using Formik in my React project to process forms and using MUI UI components.
I am able to pick the day, month, but the year part does not change. If I manually type in year in the textfield, the year part is not reflected in the changed state.
Here's my code:
<LocalizationProvider dateAdapter={DateAdapter}>
<DatePicker
name="birthday"
id="birthday"
variant="standard"
label="Birthday"
value={formik.values.birthday}
renderInput={(params) => (
<TextField {...params} variant="standard" fullWidth/>
)}
onChange={(value) => formik.setFieldValue('birthday', value, true)}
error={formik.touched.birthday && Boolean(formik.errors.birthday)}
helperText={formik.touched.birthday && formik.errors.birthday}
/>
</LocalizationProvider>
The initial state:
const initialFormState = {
birthday: Date.now(),
};
All the other components are working correctly and changes in state show immediately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于@mui-picker v6,我已经实现了此解决方案
有关更多详细信息,点击此处
For @mui-picker v6 I have implemented this solution
For more details, click here
DatePicker
组件中未设置onChange
属性。您必须将onChange
属性从TextField
移动到DatePicker
。此外,名称、id、变体和标签都是
TextField
的属性。这是工作 CodeSandbox 链接。
The
onChange
property is not set in theDatePicker
component. You have to move theonChange
property fromTextField
toDatePicker
.Also, the name, id, variant and label are
TextField
's properties.Here is the working CodeSandbox link.