【问题标题】:React 16: Call children's function from parent when using hooks and functional componentReact 16:使用钩子和功能组件时从父级调用子级函数
【发布时间】:2020-01-22 00:41:34
【问题描述】:

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

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.所有的标签都需要验证自己,在标签中显示错误信息并返回验证信息

【问题讨论】:

  • 你能补充一些关于确切要求的内容吗?
  • 嗨,克拉克,检查我的解决方案,如果有帮助,请告诉我。

标签: javascript reactjs


【解决方案1】:

您可以将useImperativeHandleforwardRef 一起使用。

来自docs

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 
   });
}

Demo

【讨论】:

  • 感谢您的回答。我在 React Native 中使用它。当您在这一行中将 ref 传递给孩子时,您能否解释一下实例发生了什么: ref={ins => refs.current[index] = ins}
  • 谢谢,但是这个声明呢? “与往常一样,在大多数情况下应避免使用 refs 的命令式代码”在这种情况下,最佳实践是什么?在 Parent 中有一个 counter,将其传递给 Child 并在 child 中使用 usePrevious 逻辑来触发 validate 方法?这不是丑陋并导致额外重新渲染 Parent 吗?还有其他最佳做法吗?
猜你喜欢
  • 2020-05-11
  • 2021-05-17
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多