如何通过按钮水平滚动点击下一个和上一个.在react native中



我正试图逐屏滚动,如屏幕1、屏幕2、屏幕3、屏幕4等,并从屏幕4滚动到屏幕3。但在下面的代码中,我只能在两个屏幕之间滚动。屏幕1和屏幕2。我想滚动更多类似屏幕3、4、5、6、7、8的内容。请帮忙。

<View style={styles.MainContainer}>
<View style={styles.ButtonViewContainer}>
<View style={styles.ButtonContainer}>
<Button
title="Previous Screen"
onPress={() => {
this.scroll.scrollTo({ x: 1 });
}}
/>
</View>
<View style={styles.ButtonContainer}>
<Button
title="Next Screen"
onPress={() => {
this.scroll.scrollTo({ x: screenWidth });
}}
/>
</View>
</View>
<ScrollView
horizontal={true}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
ref={(node) => (this.scroll = node)}
>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 1</Text>
</View>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 2</Text>
</View>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 3</Text>
</View>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 4</Text>
</View>
</ScrollView>
</View>

尝试使用npm包

https://www.npmjs.com/package/react-native-app-intro-slider

这使您可以对多屏幕的下一个和上一个进行更多控制

或者,如果你想继续现有的滚动视图管理,那么你必须管理滚动位置的当前索引,然后你可以用它管理下一个和上一个。

例如:

const App = () => {
const currIndex = useRef(0)
return (
<View style={styles.MainContainer}>
<View style={styles.ButtonViewContainer}>
<View style={styles.ButtonContainer}>
<Button
title="Previous Screen"
onPress={() => {
currIndex.current -= 1
this.scroll.scrollTo({ x: screenWidth * currIndex.current });
}}
/>
</View>
<View style={styles.ButtonContainer}>
<Button
title="Next Screen"
onPress={() => {
currIndex.current += 1
this.scroll.scrollTo({ x: screenWidth * currIndex.current });
}}
/>
</View>
</View>
<ScrollView
horizontal={true}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
ref={(node) => (this.scroll = node)}>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 1</Text>
</View>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 2</Text>
</View>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 3</Text>
</View>
<View style={styles.ScrollContainer}>
<Text style={styles.ScrollTextContainer}>Screen 4</Text>
</View>
</ScrollView>
</View>
)
}

最新更新