首页 > 解决方案 > 当它们在同一页面中时,如何使用 Hook(仅限 ForwardRef 概念)在子组件中调用父方法

问题描述

场景 1:工作正常

这是父组件

import React, { Children } from 'react'
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
    const buttonRef = React.useRef({ focusHandler: () => alert("hi") });
  
    return (
      <div>
        <ChildComponent ref={buttonRef} />
      </div>
    );
  };
export default ParentComponent;

这是使用前向引用的子组件。

import React from 'react'

const ChildComponent = React.forwardRef((props, ref) => {
    return (
      <div>
        <button onClick={ref.current.focusHandler}>Focus Input</button>
      </div>
    );
  });
  
export default ChildComponent;

场景 2:这里需要帮助

现在,如果 ParentComponent 没有 ChildComponent 并且我希望在主页中像这样调用 ChildComponent 怎么办:

MainPage.js:

import React from 'react'
import ParentComponentScenario2 from './ParentComponentScenario2';
import ChildComponentScenario2 from './ChildComponentScenario2';

const MainPage = () => {
    return (
        <div>
            <ParentComponentScenario2>
                <ChildComponentScenario2 />
            </ParentComponentScenario2>
        </div>

    )
}

export default MainPage;

父组件场景 2:

import React, { Children } from 'react'
const ParentComponentScenario2 = () => {
    const buttonRef = React.useRef({ focusHandler: () => alert("hi") });
  
    return (
      <div>
       {props.children};
      </div>
    );
  };
export default ParentComponentScenario2;

查询,我现在如何在 ChildComponent 中传递该方法,因为 <ChildComponent ref={buttonRef} />现在在页面上是不可能的。

ChildComponentScenario2:

import React from 'react'

//How to implement onClick,  props.focusHandler doesn't seem to work for some reason either.
const ChildComponentScenario2 = () => {
  return (
    <div>
       <button onClick={props.focusHandler}>Focus Input</button>
    </div>
  )
}

export default ChildComponentScenario2;

标签: javascriptreactjsreact-hooks

解决方案


您需要使用React.ChildrenAPI 和“注入”属性React.cloneElement

const ParentComponent = ({ children }) => {
  const buttonRef = React.useRef({ focusHandler: () => console.log("ref") });
  const focusHandler = () => console.log("callback");

  return (
    <div>
      {React.Children.map(children, child =>
        React.cloneElement(child, { ref: buttonRef, focusHandler })
      )}
    </div>
  );
};

const ChildComponent = React.forwardRef(({ focusHandler }, ref) => {
  return (
    <div>
      <button onClick={ref?.current.focusHandler}>Ref</button>
      <button onClick={focusHandler}>Callback</button>
    </div>
  );
});

编辑 Wizardly-diffie-14yx5


推荐阅读