React 16:使用钩子和功能组件时从父级调用子级函数

IT技术 javascript reactjs
2021-05-13 07:38:39

我需要在其父组件中调用子函数。我该怎么做?之前在 React 15 中,我可以使用 refs 来调用子函数。但是不知道如何使用钩子和功能组件来做到这一点。

function Child(props) {
    function validate() {
        // to validate this component
    }

    return (
        <>Some code here</>
    )
}


function Parent(props) {
    const refs = useRef([]);
    const someData = [1,2,3,4,5];

    function validateChildren() {
        refs.current.forEach(child => {
            child.current.validate(); // throw error!! can not get validate function
        });
    }

    return (
        <>
            <button onClick={validateChildren}>Validate</button>
            {
                someData.map((data, index) => {
                    return <Child ref={ins => refs.current[index] = ins} />
                })
            }
        </>
    )
}

我的实际需求是: 1. 有多个选项卡可以添加,根据用户行为删除 2. 单击选项卡父级中的按钮以触发验证 3. 所有选项卡都需要验证自身,在其选项卡中显示错误消息并返回一条验证消息

1个回答

您可以useImperativeHandleforwardRef.

文档中

useImperativeHandle自定义在使用 ref 时暴露给父组件的实例值。与往常一样,在大多数情况下应该避免使用 refs 的命令式代码。useImperativeHandle应该与forwardRef一起使用

const Child = React.forwardRef((props,ref) => {

    //validate will be available to parent component using ref
    useImperativeHandle(ref, () => ({
      validate() {
        // to validate this component
        console.log("I'm clicked");
      }
    }));

    return (
        <>Some code here</>
    )
})

在父组件中,您可以访问子功能,

function validateChildren() {
   refs.current.forEach(child => {
      child.validate(); // you can access child method here 
   });
}

演示