繁体   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