渲染后将 ScrollView 重置到顶部(react-navigation v4)

Reset ScrollView to the top after render (react-navigation v4)

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

我看到 post 解决方案暗示使用:

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

然后使用钩子:

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

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

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

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

使用 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
  • 添加 didFocusreact-navigation
  • 提供的侦听器
  • 使用scrollViewRef?.current?.scrollTo({x: 0, y: 0, animated: true});ScrollView滚动到顶部