【问题标题】:Automatic scroll with ScrollView in React native在 React Native 中使用 ScrollView 自动滚动
【发布时间】:2022-10-01 00:08:19
【问题描述】:

我的应用程序中有一个 cmets 列表,我希望当用户访问通知时,应用程序会自动滚动到评论。

我的代码是这样的:

cmets.tsx


const scrollViewRef = useRef(null)
const commentRef = useRef(null)

useEffect(() => {
    if(scrollViewRef.current && commentRef.current)
        commentRef.current?.measureLayout(
              scrollViewRef.current,
              (x, y) => {
                scrollViewRef.current.scrollTo({x: 0, y, animated: true})
              }
            )
}, [scrollViewRef.current, commentRef.current])

<ScrollView ref={scrollViewRef}>
        ...
        <Comments>
             {comments.map(comment => {
                 <Comment ref={commentId === commentIdNotification ? commentRef : null} />
             )}
        </Comments>
</ScrollView>

问题是 measureLayout 值通常是错误的,不会去评论。我认为这是渲染的问题,因为组件向 API 发出了多个请求,并且需要一段时间才能完成渲染。

我怎么解决这个问题?

    标签: javascript react-native react-hooks scrollview hook


    【解决方案1】:

    是否有理由使用带有地图功能的 ScrollView 而不是带有 Comment-component 作为 renderItem 的 FlatList?使用 FlatList,您可能会获得更好的控制和性能。

    在这种情况下,您可以简单地调用 FlatLists scrollToIndex()。

    请参阅此处的文档:https://reactnative.dev/docs/flatlist#scrolltoindex

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-04
      • 2019-07-16
      • 2018-04-09
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多