reactjs - 使用反应钩子从父组件触发子函数
问题描述
我在父组件中有一些操作按钮。单击其中一个按钮时,我想在子组件中触发一个功能。目前,我正在尝试使用 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 我尝试添加前向引用,但这也引发了错误。
我还发现提升状态也可能是另一种解决方案。但我无法理解如何在我的案例中应用该解决方案。有人可以帮我解决这个问题。
解决方案
警告说你在使用forwardRef
你的代码片段const ChildComponent = (({}, ref, { actionButtons, ...props }) => { .... }
,我假设这是你问题中的一个错字,你实际上是在做const ChildComponent = React.forwardRef(({}, ref,{ actionButtons, ...props }) => { .... })
.
这里的问题和警告消息指出了这一点,是您将第三个参数传递给forwardRef
它只消耗两个时。看来您从第一个论点中什么也没有解构。props
据我所知,你应该用第三个参数替换第一个参数,看起来你正在做一些道具解构。
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}/>
);
}
推荐阅读
- javascript - 当使用 `--debug` 选项时,由 `vuepress build` 生成的 VuePress 站点不会调用 `mounted()` 钩子(适用于 `vuepress dev`)
- facebook - Instagram OAuth API 返回“insufficient_dev_role”400 错误
- r - 无论我尝试什么,我都无法摆脱 NA - 缺少需要 TRUE/FALSE 的值
- php - 如果未选择第二个任何值,则首先隐藏(空)
- html - 如何在引导程序 4 中将两个输入彼此相邻放置
- html - 使用纯 css 文本的可折叠段落
- php - 有没有办法忽略并接受整理?
- graphql - 如何使查询适应 API?
- c# - Windows应用程序上的SMTP gmail
- google-cloud-platform - Cloud Run 抛出错误“错误:gcloud 崩溃(AttributeError):'Namespace' 对象没有属性'use_http2'”