如何将 withFormik 字段与 react-datepicker 一起使用?

How to use withFormik Field with react-datepicker?

我正在尝试将我的 Dob 数据从我的 Main class 发送到子组件 (RegisterAccount.jsx) 并使用 yup 和 withFormik Field 在子组件中验证它。问题是:

  1. 我无法做出 yup 或 formik/yup 来验证 dob 字段。
  2. DatePicker 在选中后不在文本框中显示选中的值。

请检查我下面的代码:

这是我的Main.jsxclass

// Some imports were removed to keep everything looks cleaner
import RegisterAccount from "RegisterAccount.jsx";

class Main extends React.Component {
     constructor(props) {
          super(props);

          this.state = {
             dob: ""
          }
     }

    render() {
        return (
            <Container fluid>
              <Switch>
                <Route exact path="/" render={() => <RegisterAccount data={this.state.dob} />} />
              </Switch>
            </Container>
        )
    }
}

export default Main;

这是我的 RegisterAccount.jsx

// Some imports were removed to keep everything looks cleaner
import { Form as FormikForm, Field, withFormik } from "formik";
import * as Yup from "yup";
import DatePicker from "react-datepicker";


const App = ({ props }) => (
  <FormikForm className="register-form  " action="">
    <h3 className="register-title">Register</h3>
    <Form.Group className="register-form-group">
      <DatePicker
         tag={Field}
         selected={props.data.dob}
         onChange={(e, val) => {
             console.log(this);
             this.value=e;
             props.data.dob = e;
             console.log(props.data.dob);
         }}
         value="01-01-2019"
         className="w-100"
         placeholderText="BIRTH DATE"
         name="dob" />
      {touched.username && errors.username && <p>{errors.username}</p>}
    </Form.Group>
  </FormikForm>
);

const FormikApp = withFormik({
  mapPropsToValues({ data }) {
    return {
      dob: data.dob || ""
    };
  },
validationSchema: Yup.object().shape({
    dob: Yup.date()
            .max(new Date())

})(App);


export default FormikApp;

使用 formik 的注入道具中的 setFieldValue 方法。

onChange 处理程序上为您的输入定义它setFieldValue('dob','Your Value')

您可以从

访问它
const MyForm = props => {
  const {
    values,
    touched,
    errors,
    handleChange,
    handleBlur,
    handleSubmit,
    setFieldValue
  } = props;
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        onChange={e => {
          setFieldValue("name", "Your value"); // Access it from props
        }}
        onBlur={handleBlur}
        value={values.name}
        name="name"
      />
    </form>
  );
};
const MyEnhancedForm = withFormik({
  // your code
})(MyForm)

参考 - https://jaredpalmer.com/formik/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean-void