withFormik(): How to use handleChange

耗尽温柔 提交于 2019-12-22 05:37:07

问题


Current platform: NodeJS (minimal), client-side React w/Redux, Formik, Yup.

Given the following example code (not including the entire React Component code since it's irrelevant to the question):

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);

...how can I use the handleChange method? I need to persist the original one (the one from Formik) while adding code that handles that checkbox change. There's some component behavior that depends on the checked value of that checkbox.

Please notice that I'm not passing the onChange prop to email or password, since there is no extra behavior to code for on those. The checkbox is the one that will have special behavior.


回答1:


You can declare a handler for the checkbox, and use it! Using the native handler of Formkit, and your custom handler.

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>
   }
}


来源:https://stackoverflow.com/questions/51159477/withformik-how-to-use-handlechange

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!