使用formik时如何将onChange添加到react-datetime?

How to add onChange to react-datetime when using formik?

我正在尝试将 onChangeformik.handleChange() 添加到 react-datetime,但它不起作用。得到一个错误。没有 onChange() 它会起作用。但是当有onChange()时就不行了。

没有 formik,它可以工作。但我还需要添加 formik

const initialValues = {
    enableReinitialize: true,
    validateOnMount: true,
    event_name: "",
    org_name: "",
    event_time: "",
    date_of_the_event: "",
    location: "",
    days_occurs: "",
    event_type: "",
    organizer_name: "",
    org_nic: "",
    cus_email: "",
    cus_con_number: "",
    description: "",
  };
const onSubmit = (values) => {
    console.log("Form Date", values);
};

  const formik = useFormik({
    initialValues,
    onSubmit,
    validationSchema,
  });

                   <Col md="6">
                      <FormGroup>
                        <label>Date of The Event</label>
                        <InputGroup className="input-group-alternative">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="ni ni-calendar-grid-58" />
                            </InputGroupText>
                          </InputGroupAddon>
                          <ReactDatetime
                            inputProps={{
                              placeholder: "Select the Date",
                              name: "date_of_the_event",
                            }}
                            timeFormat={false}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            value={formik.values.date_of_the_event}
                          />
                        </InputGroup>
                      </FormGroup>
                    </Col>

onChange of ReactDatetime return 一个值(对象 moment 或字符串)。但是 formik.handleChange 收到一个事件。所以你需要像这样更新:

onChange={(value) =>
  formik.handleChange({
    target: {
      name: "date_of_the_event",
      value,
    },
  })
}

或使用setFieldValue

onChange={(value) =>
  formik.setFieldValue("date_of_the_event", value)
}