繁体   English   中英

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

[英]handle onChange using react custom component with formik

我将自定义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 });
};

这是正确的方法,但是在每个领域处理这两个案例对我来说都是麻烦的,我不认为这是最好的方法,有帮助吗?

为什么需要两次控制该值? 您是否可以在需要时将其从表单状态中移出,而不是存储在组件状态中? 如果您进一步解释用例,我认为有人会建议一种更好的解决问题的方法。

暂无
暂无

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

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