简体   繁体   中英

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

I have 3 components, one parent component which renders 2 child components. I need to access the function of the 1st child component from the 2nd child component.

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. Is it possible without any 3rd party library like redux?

Maybe you can try with forwarding refs and useImperativeHandle .

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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