在 DatePicker
组件中选择特定日期时,如上所述出现 'handleChange is not a function' 错误。 DatePicker
组件包含在 Controller
的 react-hook-form
组件中。预期在 DatePicker
输入上显示日期。怎么解决?看下面的代码:
<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name="date"
render={({ handleDateChange, selectedDate, ref }) => (
<>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify="space-around">
<DatePicker
ref={ref}
value={selectedDate}
onChange={handleDateChange}
format={`d | ` + `MMMM | ` + `yyyy`}
disablePast
animateYearScrolling
margin="normal"
style={{ cursor: "pointer" }}
/>
</Grid>
</MuiPickersUtilsProvider>
<br />
</>
)}
rules={{
required: "Date is required"
}}
/>
</form>
这是 CodeSandbox 链接:https://codesandbox.io/s/jolly-currying-lwtrj
非常感谢任何建议或代码更改。
答案 0 :(得分:0)
首先,没有handleDateChange
或selectedDate
这样的属性,也许这就是你的意思:
render={({ onChange: handleDateChange, value: selectedDate, ref }) => (
其次,您使用的是 react-hook-form
v7,render
的 Controller
方法签名已更改。请参阅迁移指南 here。您需要从 field
属性中获取输入道具,而不是直接从渲染道具中获取:
render={({ field }) => {
const {
onChange: handleDateChange,
value: selectedDate,
ref
} = field;
完整的工作代码:
<Controller
control={control}
name="date"
render={({ field }) => {
const {
onChange: handleDateChange,
value: selectedDate,
ref
} = field;
return (
<>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify="space-around">
<DatePicker
ref={ref}
value={selectedDate}
onChange={handleDateChange}
format={`d | ` + `MMMM | ` + `yyyy`}
disablePast
animateYearScrolling
margin="normal"
style={{ cursor: "pointer" }}
/>
</Grid>
</MuiPickersUtilsProvider>
<br />
</>
);
}}
rules={{
required: "Date is required"
}}
/>