簡體   English   中英

如何從相互獨立的組件中調用 function

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

我有 3 個組件,一個父組件呈現 2 個子組件。 我需要從第二個子組件訪問第一個子組件的 function。

示例代碼:

父組件:

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

童一:

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

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

孩子二:

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

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

我需要從 childTwo 組件調用childOneFunction() 如果沒有像 redux 這樣的任何第三方庫,是否有可能?

也許您可以嘗試轉發 refsuseImperativeHandle

演示:

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