如何在 React Native ScrollView 状态更新后保持滚动位置

时间:2021-05-05 05:07:30

标签: reactjs react-native native

默认情况下,我的 React Native ScrollView 不会滚动到底部。当用户滚动到顶部时,我调用 API 并更新组件的状态,这会导致组件滚动回底部。我想在状态更新后保持当前滚动位置。

function moveCapLetter(moveCap) {
  let upr = /[A-Z]/g;
  let ul = moveCap.match(upr);

  for (let i = 0; i < ul.length; i++) {
    let m = moveCap.length;
    let indx = moveCap.indexOf(ul[i]);
    moveCap =
      moveCap.substring(0, indx) + moveCap.substring(indx + 1, moveCap.length);
  }
  moveCap = ul.join("") + moveCap;
  return moveCap;
}

1 个答案:

答案 0 :(得分:0)

创建一个引用变量

const ScrollViewRef = useRef();

然后在 ScrollView 中这样写

<ScrollView
  ref={ScrollViewRef}
  // onLayout will make sure it scroll to Bottom initially
  onLayout={() => ScrollViewRef.current.scrollToEnd()}

  // We don't need `onContentSizeChanged`
  // this onScroll fetches data  when scroll reaches top
  // then it scrolls to last position as you asked

  onScroll={({ nativeEvent }) => {
    if (ifCloseToTop(nativeEvent)) {
      handleLoadMore()
      ScrollViewRef.current.scrollTo({
        y: nativeEvent.layoutMeasurement.height,
        x: 0,
        animated: false,
      });
    }
  }}
  scrollEventThrottle={400}>
      <View style={styles.head}>
         // messages
      </View>
</ScrollView>

不要忘记在顶部导入 useRef

import {useRef} from "react-native";

工作示例here

相关问题