【问题标题】:Reset ScrollView to the top after render (react-navigation v4)渲染后将 ScrollView 重置为顶部(react-navigation v4)
【发布时间】:2021-09-17 03:30:23
【问题描述】:

每次导航到所述 ScrollView 所在的屏幕时,如何将 ScrollView 重置到其顶部? (我使用的是react-navigation v4)。

我看过一篇帖子,其中解决方案暗示使用:

import { useIsFocused } from "@react-navigation/native";

然后使用钩子:

const isFocused = useIsFocused();
useEffect(() => {
    if (isFocused) {
        scrollViewRef.current?.scrollTo(0, 0, true);
    }
}, [isFocused]);

但是,由于我使用的是 v4,因此该选项不适用于我的项目。我能做什么?

【问题讨论】:

    标签: reactjs react-native react-navigation scrollview


    【解决方案1】:

    使用react-navigation v4 an,您可以将ScrollView 滚动到屏幕焦点顶部:

    import React, {useEffect} from 'react';
    import {View, Button, ScrollView} from 'react-native';
    
    export default function Screen1({navigation}) {
      const scrollViewRef = React.createRef();
      useEffect(() => {
        const focusListener = navigation.addListener('didFocus', () => {
          scrollViewRef?.current?.scrollTo({x: 0, y: 0, animated: true});
        });
    
        return () => focusListener.remove();
      }, [navigation, scrollViewRef]);
    
      return (
        <View>
          <Button
            title={'Go to screen 2'}
            onPress={() => navigation.navigate('screen2')}
          />
          <ScrollView ref={scrollViewRef}>
            <View
              style={{
                height: 300,
                borderWidth: 1,
                marginHorizontal: 15,
                marginTop: 10,
              }}
            />
            <View
              style={{
                height: 600,
                borderWidth: 1,
                marginHorizontal: 15,
                marginTop: 10,
              }}
            />
            <View
              style={{
                height: 200,
                borderWidth: 1,
                marginHorizontal: 15,
                marginTop: 10,
              }}
            />
          </ScrollView>
        </View>
      );
    }
    
    

    基本思路是:

    • 创建ref 并将其分配给ScrollView
    • 添加react-navigation提供的didFocus监听器
    • 使用scrollViewRef?.current?.scrollTo({x: 0, y: 0, animated: true});ScrollView 滚动到顶部

    【讨论】:

      【解决方案2】:

      解决问题的一个简单方法是使用 React Ref 挂钩,只需将可滚动组件的 ref 传递给他们的 useScrollToTop 挂钩。

      import * as React from 'react'
      import { ScrollView } from 'react-native'
      import { useIsFocused } from "@react-navigation/native"
      
      
      
      function demo() {
        const ref = React.useRef(null)
      
        useIsFocused(ref)
      
        return <ScrollView ref={ref}>{/* content */}</ScrollView>
      }
      

      参考资料:

      Snack.expo.io Example

      React Navigation Documentation

      【讨论】:

        猜你喜欢
        • 2021-09-16
        • 2020-02-09
        • 1970-01-01
        • 2016-04-14
        • 2018-09-02
        • 2023-03-18
        • 2017-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多