如何在 React 的子功能组件中触发一个动作?

IT技术 reactjs typescript react-native react-functional-component react-state
2021-05-24 23:55:31

使用基本的表单/输入布局,很明显回调应该用于从子组件到父组件的状态更改(由子组件启动),但是父组件如何要求子组件重新评估其状态并将其传达回父组件?

这里的最终目标只是在提交表单按钮时触发子输入的验证。

给定的 [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}/>) 
    }

迄今为止采取的注意事项/路径:

更新 经验教训:

  • 如果您要在子组件中触发一个动作,您可以使用下面 Nadia 概述的 refs 方法,但更合适的 React Way® 可能是通过共享的 Reducer。
  • 不要期望在调用所述引用时始终通过对父级的回调来更新状态。就我而言,唯一有效的方法排序是让verify上面方法实际返回最新值。
2个回答

如何解决这个问题的简单示例

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/

在更多地了解 React 和工作解决方案的几次迭代之后,我决定使用Reducer来完成这项任务。

与其将子组件视为要调用的函数,我不得不将我的想法转变为更多地围绕更新状态并信任子组件正确表示该状态。对于我的原始示例,我最终构建了与此类似的结构(所有内容都简化并修剪了):

interface LoginState {
    email: { 
      status: 'none' | 'verify' | 'valid', 
      value?: string
    }
    password: { 
      status: 'none' | 'verify' | 'valid', 
      value?: string
    }
    submit: boolean
}
const Login : React.FC<Props> = (props) => {

        const [state, dispatch] = useReducer<Reducer>(reducer, {
            email: { status: 'none' },
            password: { status: 'none' }}
        })

        export const reducer = (state : LoginState, change : StateChange) : LoginState => {

            if (change.email) {
                state.email = _.merge({}, state.email, change.email)
            }

            if (change.password) {
                state.password = _.merge({}, state.password, change.password)
            }

            return _.merge({}, state)
        }

        const submit = () : void => {
            dispatch({
                email: { status: 'verify' }},
                password: { status: 'verify'}}},
                submit: true
            })
 
        }

        useEffect(() => {
            if (!state.submit 
                || state.email.status == 'none' 
                || state.password.satus == 'none') {
                return
            }

            //ready to submit, abort if not valid
            if (state.email.status == 'invalid'
                || state.password.status == 'invalid') {
                dispatch({ submit: false})
                return
            }

           //all is valid after this point
        }, [state.email, state.password])
        
        return (
            <Input ...
            <PasswordInput
              state={state.password}
              dispatch={dispatch} />
            <Button
              onPress={submit} />
        )
    }


    const PasswordInput : React.FC<Props> = (props) => {

        //setup onChangeText to dispatch to update value

        return (<Input
                  //do something visual with props.state.status
                  value={props.state.value}
                  onBlur={dispatch({ status: 'verify'})} ... />) 
    }

以上是粗略的代码,但要点就在那里。这传达了底层值的更新状态,这些值在中央级别减少。然后通过告诉输入它们处于 state ,在子组件级别重新呈现此状态verify当 submit 设置为 true 时,我们尝试提交表单,并在此过程中进行验证。