简体   繁体   中英

How to uses refs in React Native with Hooks?

I'm developing a React Native app with Hooks. (No Classes). When we use classes, we can create a ref to a child component like this.

<Child ref={component => this.childComponent = component} />

But, how to do this when we use Hooks?

I want something like this.

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?
  )
}

I hope you understand what I'm trying to say.

In order to define refs with hooks, you need to use useRef hook. And in order to apply ref to functional components you need to use forwardRef and useImperativeHandle 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} />  
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM