簡體   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