在 Material UI 中选择日期时出现“handleChange is not a function”错误

时间:2021-04-21 16:49:15

标签: javascript reactjs material-ui react-hook-form

DatePicker 组件中选择特定日期时,如上所述出现 'handleChange is not a function' 错误。 DatePicker 组件包含在 Controllerreact-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

非常感谢任何建议或代码更改。

1 个答案:

答案 0 :(得分:0)

首先,没有handleDateChangeselectedDate这样的属性,也许这就是你的意思:

render={({ onChange: handleDateChange, value: selectedDate, ref }) => (

其次,您使用的是 react-hook-form v7,renderController 方法签名已更改。请参阅迁移指南 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"
  }}
/>

现场演示

Edit 67200152/getting-error-as-handlechange-is-not-a-function-while-selecting-date-in-materi