当它们在同一页面中时,如何使用钩子在子组件中调用父方法(仅ForwardRef概念)

时间:2020-07-05 12:03:37

标签: javascript reactjs react-hooks

方案1:运行正常

这是ParentComponent

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;

ParentComponentScenario2:

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

查询,由于页面上现在无法<ChildComponent ref={buttonRef} />,我现在如何在ChildComponent中传递方法。

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;

1 个答案:

答案 0 :(得分:0)

您需要使用React.Children API和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>
  );
});

Edit wizardly-diffie-14yx5