【问题标题】:Invoke child method before invoking child component using react ref在使用 react ref 调用子组件之前调用子方法
【发布时间】:2021-11-05 18:08:56
【问题描述】:

我正在尝试从显示加载覆盖的父组件调用子组件中的方法。我正在使用 refs 来调用子方法。但是当我在渲染函数之前调用子方法时,ref.current 正在返回 undefined。

我关注了这个问题: userRef or createRef returning undefined in functional component

我确实在 useEffect 中添加了 ref.current,但没有任何区别。我的代码如下:

const ParentComponent = ({ actions,...props}) => {

const activeListPageRef = useRef();
    useEffect(()=>{
        console.log(activeListPageRef.current);
    });


 const getResources = async(resourceIds) => {
        console.log("activeList ref", activeListPageRef);
        if(activeListPageRef.current) {
            activeListPageRef.current.onBtShowLoading();
        }
       //fetch api
      //once done fetching on success hide the loading overlay
     activeListPageRef.current.onBTHide();
}
return (
 < childComponent ref={activeListPageRef} />
)
}

const ChildComponent =({ tableData,  ...props}, ref) => {

const onBtShowLoading = () => {
        gridApi.showLoadingOverlay();
      };
}

useImperativeHandle(ref, () => ({
        onGridReady,
        onBtShowLoading,
        onBtHide
    }));

如何在调用子组件之前引用子组件方法?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您需要移动打算在useEffect 内部使用 ref 的逻辑,以便它仅在创建子组件并定义 ref 后运行。

    下面的代码应该可以工作(见this codesandbox):

    子组件

    import React, { useImperativeHandle, forwardRef } from "react";
    
    const ChildComponent = (props, ref) => {
      const onBtShowLoading = () => {
        console.log("onBtShowLoading was called!");
        // Actual implementation here.
      };
    
      const onBTHide = () => {
        console.log("onBtHide called");
        // Actual implementation here.
      };
    
      useImperativeHandle(ref, () => ({
        onBtShowLoading,
        onBTHide
      }));
      return <div>Child Component</div>;
    };
    
    export default forwardRef(ChildComponent);
    

    父组件

    import React, { useRef, useEffect } from "react";
    import ChildComponent from "./ChildComponent";
    
    const ParentComponent = ({ actions, ...props }) => {
      const activeListPageRef = useRef();
      useEffect(() => {
        // This code will run after the component renders the first time
        // So activeListPageRef.current will be defined.
        const getResources = async (resourceIds) => {
          if (activeListPageRef.current) {
            activeListPageRef.current.onBtShowLoading();
          }
          activeListPageRef.current.onBTHide();
        };
        // Because useEffect doesn't support async functions directly
        // you have to define the function first, then call it.
        getResources();
      });
    
      return <ChildComponent ref={activeListPageRef} />;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2018-09-10
      • 2021-01-06
      • 2018-07-20
      • 1970-01-01
      • 2017-02-27
      • 2017-10-19
      • 2016-12-03
      相关资源
      最近更新 更多