React防止子更新

5lhxktic  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(232)

我有一个简单的for,其中包含一些字段,这些字段是该表单的子组件。每个字段都验证其自身的值,如果更改,则应向父字段报告,这会导致字段重新渲染并失去焦点。我想要一个子组件不更新的行为。这是我的密码:
家长(表格):

function Form() {

    const [validFields, setValidFields] = useState({});

    const validateField = (field, isValid) => {
        setValidFields(prevValidFields => ({ ...prevValidFields, [field]: isValid }))
    }

    const handleSubmit = (event) => {
        event.preventDefault();
        //will do something if all fields are valid
        return false;
    }

    return (
        <div>
            <Title />
            <StyledForm onSubmit={handleSubmit}>
                <InputField name="fooField" reportState={validateField} isValidCondition={fooRegex} />
                <Button type="submit" content="Enviar" maxWidth="none" />
            </StyledForm>
        </div>
    );
}

export default Form;

子项(字段):

function InputField(props) {

    const [isValid, setValid] = useState(true);
    const [content, setContent] = useState("");
    const StyledInput = isValid ? Input : ErrorInput;

    const validate = (event) => {
        setContent(event.target.value);
        setValid(stringValidator.validateField(event.target.value, props.isValidCondition))
        props.reportState(props.name, isValid);
    }

    return (
        <Field>
            <Label htmlFor={props.name}>{props.name + ":"}</Label>
            <StyledInput
                key={"form-input-field"}
                value={content}
                name={props.name}
                onChange={validate}>
            </StyledInput>
        </Field>
    );
}

export default InputField;

通过设置 key 对于我的子元素,我能够防止它在内容更改时失去焦点。我想我想要实现 shouldComponentUpdate 如react文档中所述,我尝试通过执行以下操作来实现它:
尝试1:用react.memo包围孩子

const InputField = React.memo((props) {
    //didn't change component content
})

export { InputField };

尝试2:使儿童与 useMemo 关于父母

const fooField = useMemo(<InputField name="fooField" reportState={validateField} isValidCondition={fooRegex} />, [fooRegex]);

    return (
        <div>
            <Title />
            <StyledForm onSubmit={handleSubmit}>
                {fooField}
                <Button type="submit" content="Enviar" maxWidth="none" />
            </StyledForm>
        </div>
    );

两个都不起作用。如何使其在子组件为有效状态时不重新渲染?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题