首页 > 解决方案 > React Hooks - 带有钩子的功能组件中 ScrollView 的引用?

问题描述

我将一个反应原生项目从所有类组件转换为带有钩子的功能组件。我有一个带有自动滚动到底部的 ScrollView 的消息传递页面。我如何将其转换为在功能组件中工作?使用 ref 和 this.scrollView 会导致错误。

<ScrollView 
   ref={ref => this.scrollView = ref}
   onContentSizeChange={(contentWidth, contentHeight)=> {this.scrollView.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>

标签: reactjsreact-native

解决方案


在组件的主体中:

function App(props) {    
   const scrollViewRef = useRef();
...

在组件上:

<ScrollView 
   ref={scrollViewRef}
   onContentSizeChange={(contentWidth, contentHeight)=> {scrollViewRef.current.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>

推荐阅读