【问题标题】:Accessing refs in React Native custom functional components在 React Native 自定义功能组件中访问 refs
【发布时间】:2021-07-11 09:10:40
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

标签: reactjs react-native ref


【解决方案1】:

可以使用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} />;

【讨论】:

  • 您还必须为孩子申请forwardRef,否则这将不起作用。
猜你喜欢
  • 1970-01-01
  • 2022-11-12
  • 2016-08-11
  • 2020-03-11
  • 2018-08-09
  • 2020-12-06
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
相关资源
最近更新 更多