在 React Native 中,父组件调用子组件的方法可以通过 ref 属性来实现。

首先,在子组件中定义一个方法:

function ChildComponent(props, ref) {
  const myMethod = () => {
    // ...
  };

  // 将方法暴漏给父组件
  React.useImperativeHandle(ref, () => ({
    myMethod,
  }));

  // ...
}

// 将子组件包装成 forwardRef 组件
const ForwardedChildComponent = React.forwardRef(ChildComponent);

然后,在父组件中创建一个 ref,并将其传递给子组件:

function ParentComponent() {
  // 创建一个 ref
  const childRef = React.useRef();

  // 在需要的时候调用子组件方法
  const handleButtonClick = () => {
    childRef.current.myMethod();
  };

  return (
    <>
      <ForwardedChildComponent ref={childRef} />
      <Button title="调用子组件方法" onPress={handleButtonClick} />
    </>
  );
}

通过 forwardRef 和 useImperativeHandle,我们可以在函数式组件中方便地暴漏子组件的方法,来供父组件调用。


原文地址: https://www.cveoy.top/t/topic/bPLm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录