对于基本的表单/输入布局,很明显应该使用回调来处理从子组件到父组件的状态更改(由子组件发起),但是父组件如何要求子组件重新评估其状态并将其传达回父组件?
这里的最终目标只是在提交表单按钮时触发子输入的验证。
给定的 [ts] 代码如下所示:
const Login : React.FC<Props> = (props) => {
...useStates omitted
const onSubmit = () : void => {
//trigger `verify()` in PasswordInput to get up-to-date `valid` state var
}
return (
<PasswordInput
onValidChange={setValid} />
<Button
onPress={submit} />
)
}
const PasswordInput : React.FC<Props> = (props) => {
...useStates omitted
const verify = () => {
//verify the password value from state
props.onValidChange(true)
}
return (<Input onBlur={verify}/>)
}
迄今为止采取的注释/路径:
- 您不能在函数组件上使用 ref 属性,因为它们没有实例。 https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs
- 尝试使用
useEffect
更新一个submitted
状态变量确实有效地触发了重新验证,但排序useEffect
总是在父组件评估之后出现onSubmit
,导致值过时。 IE。在提交之前需要点击两次提交valid
变量是最新的。
- 反应版本 16.14.4
UPDATE得到教训:
- 如果您要在子组件中触发操作,您可以使用下面 Nadia 概述的 refs 方法,但更合适的 React Way® 可能是通过共享Reducer。
- 不要期望在调用所述引用时始终通过对父级的回调来更新状态。就我而言,唯一有效的排序方法是获得
verify
上面的方法实际上返回最新的值。
一个简单的例子说明如何解决这个问题
function Child(props)
{
const validate=()=> alert('hi from the child');
props.registerCallback(validate)
return (<div>I'm the child</div>)
}
function Parent()
{
const callbackRef = React.useRef();
function registerCallback(callback)
{
callbackRef.current = callback;
}
return (<div><Child registerCallback={registerCallback}/>
<button onClick={() => callbackRef.current()}>say hello</button></div>)
}
https://jsfiddle.net/4howanL2/5/ https://jsfiddle.net/4howanL2/5/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)