如何在 React Native ScrollView 状态更新后保持滚动位置
How to keep scroll position after state update in React Native ScrollView
默认情况下,我不会让我的 React Native ScrollView 滚动到底部。当用户滚动到顶部时,我调用 API 并更新组件的状态,这会导致组件滚动回底部。我想在状态更新后保持当前滚动位置。
const ifCloseToTop = ({ layoutMeasurement, contentOffset, contentSize }) => {
return contentOffset.y == 0;
};
<ScrollView
ref={scrollViewRef}
onContentSizeChange={(contentWidth, contentHeight) => {
scrollViewRef.current.scrollTo({y:0, animated: true }) }} // this is for initial keeping scroll to bottom
onScroll={({ nativeEvent }) => {
if (ifCloseToTop(nativeEvent)) {
handleLoadMore()
console.log('top')// this function on scroll top api call and state update, but on each update goes to initial bottom position, i want scroll to be current after state update
}
}}
scrollEventThrottle={400}
>
<View style={styles.head}>
// messages
</View>
</ScrollView>`
创建一个引用变量
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
默认情况下,我不会让我的 React Native ScrollView 滚动到底部。当用户滚动到顶部时,我调用 API 并更新组件的状态,这会导致组件滚动回底部。我想在状态更新后保持当前滚动位置。
const ifCloseToTop = ({ layoutMeasurement, contentOffset, contentSize }) => {
return contentOffset.y == 0;
};
<ScrollView
ref={scrollViewRef}
onContentSizeChange={(contentWidth, contentHeight) => {
scrollViewRef.current.scrollTo({y:0, animated: true }) }} // this is for initial keeping scroll to bottom
onScroll={({ nativeEvent }) => {
if (ifCloseToTop(nativeEvent)) {
handleLoadMore()
console.log('top')// this function on scroll top api call and state update, but on each update goes to initial bottom position, i want scroll to be current after state update
}
}}
scrollEventThrottle={400}
>
<View style={styles.head}>
// messages
</View>
</ScrollView>`
创建一个引用变量
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