如何通过 Hooks 在 React Native 中使用 refs?

Sen*_*ika 5 javascript ref react-native react-hooks

我正在使用 Hooks 开发一个 React Native 应用程序。(无课程)。当我们使用类时,我们可以像这样创建对子组件的引用。

<Child ref={component => this.childComponent = component} />
Run Code Online (Sandbox Code Playgroud)

但是,当我们使用 Hooks 时,该怎么做呢?

我想要这样的东西。

export default function Child() {
  const foo = () => {
    //do something
  }

  return(
    //something
  )
}


export default function Parent() {
  const myFunc = () => {
    ref.foo();
  }

  return(
    <Child ref={.........} />  //This is what I want to know how to do?
  )
}
Run Code Online (Sandbox Code Playgroud)

我希望你明白我想说的。

Shu*_*tri 7

为了用钩子定义引用,你需要使用useRef钩子。为了将 ref 应用于功能组件,您需要使用forwardRefuseImperativeHandle hook

function Child(props, ref) {
  const foo = () => {
    //do something
  }

  useImperativeHandle(ref, () => ({
     foo
  }));

  return(
    //something
  )
}

export default React.forwardRef(Child)


export default function Parent() {
  const childRef = useRef(null)
  const myFunc = () => {
    childRef.current.foo();
  }

  return(
    <Child ref={childRef} />  
  )
}
Run Code Online (Sandbox Code Playgroud)