admin管理员组

文章数量:1397102

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

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

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.

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

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

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.

Share Improve this question asked Apr 27, 2020 at 11:29 Sennen RandikaSennen Randika 1,6463 gold badges17 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: javascriptHow to uses refs in React Native with HooksStack Overflow