React Native详情页上下页导航按钮实现方案咨询
实现详情页的「下一页」和「返回」导航功能
核心实现逻辑
- 在详情页引入
people数组,通过当前页面接收的参数定位该对象在数组中的索引 - 「返回」按钮直接调用导航的
goBack()方法回到上一页 - 「下一页」按钮根据当前索引判断是否存在后续对象,若存在则跳转至对应详情页,若已是最后一项则禁用按钮
修改后的EachPage.js代码
import React from "react"; import { View, Text, Button } from "react-native"; import people from "./people"; function EachPage({ route, navigation }) { const currentPerson = route.params; // 匹配当前对象在数组中的索引 const currentIndex = people.findIndex(person => person.id === currentPerson.id); // 判断是否存在下一个对象 const hasNext = currentIndex < people.length - 1; const handleNext = () => { if (hasNext) { const nextPerson = people[currentIndex + 1]; navigation.navigate("EachPage", nextPerson); } }; return ( <View> <Text>{currentPerson.id}</Text> <Text>{currentPerson.name}</Text> <Button title="Next" onPress={handleNext} disabled={!hasNext} /> <Button title="Back" onPress={() => navigation.goBack()} /> </View> ); } export default EachPage;
关键细节说明
- 使用
findIndex通过id匹配索引,确保数组顺序变动时仍能准确定位 - 当处于最后一项时,「下一页」按钮自动禁用,避免无效跳转
navigation.goBack()直接返回上一级页面,符合原生导航的返回逻辑
内容的提问来源于stack exchange,提问作者sahasrabhuja neuron
相关产品推荐
相关产品推荐

