【发布时间】: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