React Native:点击用户后展示该用户并支持滑动切换其他用户
解决React Native详情页左右滑动切换用户的问题
我看了你的代码,问题根源很清晰:你的详情页虽然用了Swiper遍历state.items,但所有UI内容都是从navigation.getParam里取当前点击的单个用户数据,导致每个Swiper页面渲染的都是同一个用户,自然滑动看不到其他用户。另外,大概率你跳转详情页时只传了当前用户的信息,没有把整个用户列表传过去,或者state.items根本没正确拿到全量数据。
下面是一步步的修复方案:
1. 修改FlatList跳转时的传参逻辑
在你的_displayDetailForUser函数里,除了传当前用户的信息,还要把整个用户列表和当前用户的索引一起传给详情页。这样详情页才能拿到所有用户数据,知道从哪个位置开始滑动:
_displayDetailForUser = (item, index) => { this.props.navigation.navigate('UserDetail', { user: item, userList: this.state.dataSource, // 传整个用户列表 currentIndex: index // 传当前点击的索引 }); };
然后在FlatList的renderItem里把索引传过去:
renderItem={({item, index}) => <UserItem user={item} displayDetailForUser={() => this._displayDetailForUser(item, index)} />}
2. 重构详情组件的逻辑
首先在详情组件的componentDidMount里接收导航参数,把全量用户列表存到state,同时设置Swiper的初始页面:
componentDidMount() { const { navigation } = this.props; const userList = navigation.getParam('userList', []); const currentIndex = navigation.getParam('currentIndex', 0); this.setState({ items: userList, activeIndex: currentIndex // 记录当前活跃的索引 }); }
然后修改你的render逻辑,遍历state.items时,使用当前遍历的item数据,而不是一直取导航参数里的单个用户:
render () { return ( <Swiper showsPagination={false} index={this.state.activeIndex} // 设置初始显示的页面 onIndexChanged={(index) => this.setState({activeIndex: index})} // 记录滑动后的索引 > {this.state.items.map((item, key) => { // 针对每个item计算在线状态颜色 const colorConnected = item.Statut === "ON" ? "#1fbc26" : item.Statut === "OFF" ? "#ff0303" : "#ffd200"; return ( <ScrollView key={item.MembreId} style={styles.view_container}> <View style={styles.photo}> <ImageBackground source={{uri: item.Photo}} style={{ width: '100%', height: '100%' }}> <View style={styles.photo_content}> <LinearGradient colors={['transparent', 'rgba(0,0,0,0.5)']} style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 80 }} /> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <View> <Text style={{ fontSize: 40, color:'white' }}>{item.Age}</Text> </View> <View style={{ marginRight: 7, marginLeft: 7, backgroundColor: '#ffffff', width: 1, height: 39 }}></View> <View style={{ flexDirection: 'column', flex:1 }}> <View style={{ flexDirection: 'row' }}> <View style={[styles.bulle_presence, { backgroundColor: colorConnected } ]}></View> <Text style={{ fontSize: 18, fontWeight: '600', color:'white' }}>{item.Pseudo}</Text> </View> <View style={{ flexDirection: 'row', justifyContent: 'space-between'}}> <Text style={{ fontSize: 15, color:'white' }}>{item.Distance}</Text> <Text style={{ fontSize: 15, color:'white'}}>{item.Genre}</Text> </View> </View> </View> </View> </ImageBackground> </View> {/* 其他用户详情内容 */} </ScrollView> ) })} </Swiper> ) }
关键修复点说明
- 传全量列表:之前详情页没有拿到所有用户数据,自然无法渲染其他用户;现在把整个列表传过去,Swiper才能生成对应数量的页面。
- 使用遍历的item数据:之前所有页面都用
navigation.getParam的单个用户,导致每个页面内容完全一致,滑动看不出变化;现在每个页面用当前遍历的item,内容才会不同。 - 设置初始索引:让Swiper打开时直接定位到用户点击的那个用户,提升体验。
这样修改后,你的详情页就能左右滑动切换所有用户了。
内容的提问来源于stack exchange,提问作者Jats1596
相关产品推荐
相关产品推荐

