【问题标题】:How to uses refs in React Native with Hooks?如何在 React Native with Hooks 中使用 refs?
【发布时间】:2020-08-10 22:47:01
【问题描述】:

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

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

但是,当我们使用 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?
  )
}

我希望你明白我想说什么。

【问题讨论】:

    标签: javascript react-native react-hooks ref


    【解决方案1】:

    为了定义带有钩子的引用,你需要使用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} />  
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-10
      • 2021-11-24
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多