简体   繁体   English

使用带有formik的react自定义组件来处理onChange

[英]handle onChange using react custom component with formik

I use custom react component with formik which is handled by sending the value where I use it and setting its own state from its parent, so onChange I am always set its react state besides setFieldvalue to set it in formik as I dont use handleChange from formik props. 我将自定义react组件与formik一起使用,该组件通过在我使用它的位置发送值并从其父级设置其自身状态来进行处理,因此onChange我总是将其setResetvalue设置为在setik中设置它的反应状态,因为我不使用formik中的handleChange道具。

     <Field
    render={(fields: { field: object; form: formProps }) => {
        return (
            <TextField
            name="title"
            error={errors.title && touched.title}
            value={title}
            onKeyUp={() => null}
            onBlur={handleBlur}
            onChange={(e: { target: { value: string } }) =>
                this.props.onChange('title', e, fields.form)
            }
            placeholder="e.g Introduction to UX Design"
            />
        );
    }}
/>

onChange = (
    stateField: string,
    e: { target: { value: string } },
    form: { setFieldValue: (field: string, value: string) => void }
) => {
// the field is controlled twice here
    form.setFieldValue(stateField, e.target.value);
    this.setState({ [stateField]: e.target.value });
};

it is working correct but it is a hassle for me to handle the two cases in each field and I am not feeling it is the best way to do so, any help ? 这是正确的方法,但是在每个领域处理这两个案例对我来说都是麻烦的,我不认为这是最好的方法,有帮助吗?

Why do you need to control the value twice? 为什么需要两次控制该值? Can you not lift it out of the form state when required, rather than storing in the component state? 您是否可以在需要时将其从表单状态中移出,而不是存储在组件状态中? If you explain the use case more, I think someone will suggest a better way of tackling the problem. 如果您进一步解释用例,我认为有人会建议一种更好的解决问题的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM