【问题标题】:Trigger child function from parent component using react hooks使用反应钩子从父组件触发子函数
【发布时间】:2021-08-03 19:52:46
【问题描述】:

我在父组件中有一些操作按钮。单击其中一个按钮时,我想在子组件中触发一个功能。目前,我正在尝试使用 useRef 挂钩来实现它。但解决方案似乎很乏味,也给了我警告:

我当前的代码如下:

import React, {useContext, useEffect, useState, useRef} from 'react';
const ParentComponent = ({...props})=> {
const myRef = useRef();
const onClickFunction = () => {
        if(myRef.current) {
            myRef.current.childFunction();
        }
    }
return (
<ChildComponent ref = {myRef}/>
);
}

子组件

const ChildComponent = (({}, ref,{  actionButtons, ...props}) => {
const [childDataApi, setChildDataApi] = useState(null);

const childFunction = () => {
       //update childDataApi and pass it to parent
        console.log("inside refreshEntireGrid");
    }
});

首先,有没有更好的解决方案然后尝试从 parent 触发 childFunction ?为此,我正在遵循此解决方案: Can't access child function from parent function with React Hooks 我尝试添加前向引用,但这也引发了错误。

我还发现提升状态也可能是另一种解决方案。但我无法理解如何在我的案例中应用该解决方案。有人可以帮我解决这个问题吗?

【问题讨论】:

  • linked 的解决方案是将引用转发到子组件并强制调用函数的正确解决方案。在这个实现中什么对你不起作用?您能否更新您的问题以包括您尝试过的内容以及问题/错误是什么?
  • 当然!我在该解决方案链接和它给我的警告之后添加了我如何使用 forwardRef。

标签: reactjs


【解决方案1】:

警告说你使用的是forwardRef,所以你的sn-p const ChildComponent = (({}, ref, { actionButtons, ...props }) =&gt; { .... }我假设这是你的问题中的一个错字,而你实际上是在使用const ChildComponent = React.forwardRef(({}, ref,{ actionButtons, ...props }) =&gt; { .... })

这里的问题和警告消息指出了这一点,是您将第三个参数传递给forwardRef,而它只消耗了两个。您似乎从第一个 props 参数中解构了 nothing。据我所知,你应该用第三个参数替换第一个参数,看起来你正在做一些道具解构。

const ChildComponent = React.forwardRef(({ actionButtons, ...props }, ref) => { .... }

从这里你应该实现 useImperativeHandle 钩子以从子项中公开函数。

const ChildComponent = React.forwardRef(({ actionButtons, ...props }, ref) => {
  const [childDataApi, setChildDataApi] = useState(null);
  
  const childFunction = () => {
    // update childDataApi and pass it to parent
    console.log("inside refreshEntireGrid");
  }

  useImperativeHandle(ref, () => ({
    childFunction
  }));

  ...

  return ( ... );
});

在父组件中:

const ParentComponent = (props) => {
  const myRef = useRef();

  const onClickFunction = () => {
    myRef.current?.childFunction();
  }

  return (
    <ChildComponent ref={myRef}/>
  );
}

【讨论】:

  • 谢谢!这个解决方案奏效了。我错误地使用了 useImperativeHandle。
【解决方案2】:

您可以尝试的其他方法是向子组件传递一个 prop 以指示该按钮已被单击,并在子组件中使用 useEffect 在该值更改时执行某些操作。

const Child = props => {
  useEffect(() => TriggeredFunc(), [props.buttonClicked]);

  const TriggeredFunc = () => {
    ...
  }

  return '...';
}

const Parent = () => {
  const [buttonClicked, setButtonClicked] = useState(0);

  const onClick = e => {
    setButtonClicked(buttonClicked++);
  }

  return <>
    <button onClick={onClick}>My Button</button>
    <Child buttonClicked={buttonClicked} />;
  </>

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2019-07-11
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多