强制重新评估子组件
Forcing reevaluation of child component
我有一个使用自定义 <Input>
元素的表单。在 Input
组件中,我管理输入的状态 (valid/invalid)。在表单中,我要求用户重新输入密码,我希望如果用户正确输入两个密码然后修改第一个密码,第二个密码将无效(获得红色背景色)。
所以在 Form
组件中,我想在每次第一个密码的值更改时触发对第二个密码 Input
的重新评估。
在 Form
中,我将第一个密码的值存储在 useReducer
状态中,我认为在组件的 props
中传递它会自动触发重新评估,但事实并非如此。
Password
[*****_____]
Re-enter Password
[*****_____] // "valid" because it has the same value of the first password
...then the user modify the first password:
Password
[********__]
Re-enter Password
[*****_____] // this component should be reevaluated and set itself to "invalid"
我这里在第二个组件的props中传递第一个密码的值:
<Input
...props...
testingFunction={password => password && password === formState.password.value}
/>
我还尝试通过添加此 属性 来更明确地传递值:dependencies={formState.password.value}
,但它也不起作用。
那么这种方法有什么问题,强制重新评估第二个密码组件的好方法是什么?
您可以在 Input
组件中使用 useEffect 到 运行 您的 re-evaluation
。
例如
import React, { useEffect } from "react";
interface IInputProps extends HTMLInputElement {
reevaluate?: string;
}
const Input: React.FC<IInputProps> = (props: IInputProps) => {
useEffect(() => {
console.log("Run your evaluation code here - This code block will be run whenever `reevaluate` prop is changed");
}, [props.reevaluate])
return (
<input type="text" />
);
};
我有一个使用自定义 <Input>
元素的表单。在 Input
组件中,我管理输入的状态 (valid/invalid)。在表单中,我要求用户重新输入密码,我希望如果用户正确输入两个密码然后修改第一个密码,第二个密码将无效(获得红色背景色)。
所以在 Form
组件中,我想在每次第一个密码的值更改时触发对第二个密码 Input
的重新评估。
在 Form
中,我将第一个密码的值存储在 useReducer
状态中,我认为在组件的 props
中传递它会自动触发重新评估,但事实并非如此。
Password
[*****_____]
Re-enter Password
[*****_____] // "valid" because it has the same value of the first password
...then the user modify the first password:
Password
[********__]
Re-enter Password
[*****_____] // this component should be reevaluated and set itself to "invalid"
我这里在第二个组件的props中传递第一个密码的值:
<Input
...props...
testingFunction={password => password && password === formState.password.value}
/>
我还尝试通过添加此 属性 来更明确地传递值:dependencies={formState.password.value}
,但它也不起作用。
那么这种方法有什么问题,强制重新评估第二个密码组件的好方法是什么?
您可以在 Input
组件中使用 useEffect 到 运行 您的 re-evaluation
。
例如
import React, { useEffect } from "react";
interface IInputProps extends HTMLInputElement {
reevaluate?: string;
}
const Input: React.FC<IInputProps> = (props: IInputProps) => {
useEffect(() => {
console.log("Run your evaluation code here - This code block will be run whenever `reevaluate` prop is changed");
}, [props.reevaluate])
return (
<input type="text" />
);
};