【问题标题】:How to add onChange to react-datetime when using formik?使用formik时如何将onChange添加到react-datetime?
【发布时间】:2021-10-19 08:28:12
【问题描述】:

我正在尝试将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>

【问题讨论】:

    标签: reactjs onchange formik react-datetime


    【解决方案1】:

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

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

    或使用setFieldValue

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

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 2019-03-22
      • 2021-03-08
      • 2022-08-22
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多