withFormik():如何使用handleChange

IT技术 reactjs formik
2021-05-10 15:35:22

当前平台:NodeJS(最小),客户端 React w/Redux,Formik,是的。

给出以下示例代码(不包括整个 React 组件代码,因为它与问题无关):

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

    // (...)

    render () {
        <Form>
            <Field name="email" type="email" />
            <Field name="password" type="password" />
            <Field 
                name="myCheckbox" 
                type="checkbox"
                checked={this.props.values.myCheckbox}
                onChange={  ??????????  } />
        </Form>
    }
}

const handleFormSubmission = (values, { resetForm, setErrors, setSubmitting }) => {
    console.log(values);
};

const handleFormChange = (event) => {
    event.persist();
    console.log('changed');
};

const MyFormik = withFormik({
    mapPropsToValues ({ email, password, myCheckbox }) {
        return {
            email: email || '',
            password: password || '',
            myCheckbox: myCheckbox || false
       }
    },
    validationSchema: (...Yup schema here...),
    handleSubmit (values, bag) { return handleFormSubmission(values, bag); }
})(RegisterPage);

export default connect()(MyFormik);

...我如何使用 handleChange 方法我需要保留原始的(来自 Formik 的),同时添加处理该复选框更改的代码。有一些组件行为取决于该复选框的选中值。

请注意,我没有将 onChange props传递给电子邮件或密码,因为没有额外的行为可以为它们编码。复选框是具有特殊行为的复选框。

2个回答

您可以为复选框声明一个处理程序,然后使用它!使用 Formkit 的本机处理程序和您的自定义处理程序。

class RegisterPage extends React.Component {
   constructor(props) {
      super(props);
   }
   // (...)
   handleCheckBox: (e) => {
       // do whatever you want to the value
   }
   render () {
       <Form>
           <Field name="email" type="email" />
           <Field name="password" type="password" />
           <Field 
               name="myCheckbox" 
               type="checkbox"
               checked={this.props.values.myCheckbox}
               onChange={(e) => {this.props.handleChange(e); this.handleCheckBox(e)}} />
       </Form>
   }
}

以防万一,如果你想处理复选框

onChange={(e, event) => {
   handleChange({ ...event, target: { name: 'isDeleted', value: e } })
}}