首页 > 解决方案 > 使用反应钩子从父组件触发子函数

问题描述

我在父组件中有一些操作按钮。单击其中一个按钮时,我想在子组件中触发一个功能。目前,我正在尝试使用 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 我尝试添加前向引用,但这也引发了错误。 在此处输入图像描述

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

标签: reactjs

解决方案


警告说你在使用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}/>
  );
}

推荐阅读