相关疑难解决方法(0)

为什么,确切地说,我们需要 React.forwardRef?

假设我有一个带有可滚动子组件的组件,并且我想公开滚动的能力:

const MyComponent = (props) => {
    return <ScrollView ... />
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做到

<MyComponent ref={myRef} />

...

myRef.scrollTo({x: 0});
Run Code Online (Sandbox Code Playgroud)

所以我需要一种方法将 ref 转发到<ScrollView>. 让我们尝试将 ref 放在 props 上:

const MyComponent = (props) => {
    return <ScrollView ref={props.scrollRef} ... />
}

...

<MyComponent scrollRef={myRef} />

...

myRef.scrollTo({x: 0});
Run Code Online (Sandbox Code Playgroud)

我刚刚在 iOS 上用 React Native 尝试过,它确实有效。我看到了几个优点React.forwardRef

  • 更简单,因为我不需要使用另一个 React API。
  • 如果有多个孩子需要参考转发,也可以使用。
  • 在我看来,这种方法是

有什么好处React.forwardRef?为什么在 React 16.3 中添加它?

reactjs react-native

9
推荐指数
1
解决办法
3388
查看次数

标签 统计

react-native ×1

reactjs ×1