简体   繁体   English

如何从相互独立的组件中调用 function

[英]how to call function from component that is independent of each other

I have 3 components, one parent component which renders 2 child components.我有 3 个组件,一个父组件呈现 2 个子组件。 I need to access the function of the 1st child component from the 2nd child component.我需要从第二个子组件访问第一个子组件的 function。

Sample Code:示例代码:

Parent Component:父组件:

class Main extends React.Component {
myRef: React.RefObject<any>;
constructor(props: any) {
super(props);
  this.myRef = React.createRef();
}
  return (
    <div>
      {/* some code */}
      <ChildOne />
      <ChildTwo />
    </div>
  );

ChildOne:童一:

function ChildOne() {
  const childOneFunction = () => {
    console.log("Hello from child one");
  };

  return <div>{/* some code */}</div>;
}
}

ChildTwo:孩子二:

function ChildTwo() {
  useEffect(() => {
    childOneFunction();
  });

  return <div>{/* some code */}</div>;
}

I need call the childOneFunction() from childTwo component.我需要从 childTwo 组件调用childOneFunction() Is it possible without any 3rd party library like redux?如果没有像 redux 这样的任何第三方库,是否有可能?

Maybe you can try with forwarding refs and useImperativeHandle .也许您可以尝试转发 refsuseImperativeHandle

Demo:演示:

let ChildOne = React.forwardRef((props, ref) => {
  React.useImperativeHandle(ref, () => ({
    childOneFunction: () => {
      console.log('Hello from child one');
    },
  }));

  return <div>1</div>;
});

let ChildTwo = React.forwardRef((props, ref) => {
  return (
    <div
      onClick={() => {
        ref.current.childOneFunction();
      }}
    >
      2
    </div>
  );
});

export default function App() {
  const test = React.useRef();

  return (
    <div>
      <ChildOne ref={test} />
      <ChildTwo ref={test} />
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM