在 React Native 自定义功能组件中访问 refs

Accessing refs in React Native custom functional components

我想在父组件中调用子组件的功能。这是我的伪代码:

export const Child: React.FC<Props> = ({ onRef }) => {
  useEffect(() => {
    if (onRef) {
      onRef(this);
    }
  }, [])

  function callMe() {
    console.log('Child has been called');
  }

  return <Text>Child</Text>;
}

export const Parent: React.FC<Props> = () => {
  const childRef = useRef(null);

  function callChild() {
    childRef.current.callMe();
  }

  return <Child onRef={childRef} />;
}

我该怎么做?

可以使用useImperativeHandle调用子组件功能

您可以在子组件中像这样定义您的函数。

useImperativeHandle(ref, () => ({
  callMe: () => {
    console.log('Child has been called');
  }
}));

此外,您还应将forwardRef应用于子组件:

export const Child = forwardRef(props, ref) => {
  // component logic
});

现在您可以通过在父组件中创建一个 ref 来调用此函数,如下所示:

const childRef = useRef(null);

function callChild() {
  childRef.current.callMe();
}

return <Child ref={childRef} />;