React Native 开发中如何实现帖子区域的横向滚动功能?
实现方案
直接按下面3步改就能实现需求:
- 调整数据结构,先把帖子按用户分组
你现在的代码是硬编码每个Posts组件,要先把同一用户的帖子归到一组,在Home的state里新增分组数据,示例:
state={ popularSelected:true, // 新增按用户分组的帖子数据 postGroups: [ { userId: 1, name: "Max Bator", profile: require('../images/p1.jpg'), posts: [ {id: 101, photo: require('../images/5.jpg'), liked: false}, {id: 102, photo: require('../images/3.jpg'), liked: false}, // 追加该用户的其他帖子 ] }, { userId: 2, name: "Erka Berka", profile: require('../images/p2.jpg'), posts: [ {id: 201, photo: require('../images/6.jpg'), liked: false}, // 追加该用户的其他帖子 ] } ] }
- 拆分原有Posts组件
原来的Posts组件把用户头部信息和单条帖子内容绑在一起了,同一用户的多条帖子只需要展示一次用户头,所以把组件拆成两部分:用户头部、单条帖子内容。也可以直接把逻辑写到Home的渲染里,不用单独拆组件也行,看你习惯。 - 替换Home里的硬编码帖子渲染逻辑
把原来Home里写死的几个Posts渲染块,换成遍历分组数据+横向ScrollView的逻辑,示例:
{/* 把原来硬编码的三个帖子View直接替换成下面这段 */} {this.state.postGroups.map(group => ( <View key={group.userId} style={{marginVertical: 15}}> {/* 同一用户只渲染一次头部信息 */} <View style={{ flexDirection:"row", paddingTop:25, alignItems:"center" }}> <View style={{width:"20%"}}> <Image source={group.profile} style={{ width:45, height:45, borderRadius:13 }} /> </View> <View style={{width:"60%"}}> <Text style={{ fontFamily:"Bold", fontSize:14, color:"#044244" }}>{group.name}</Text> <Text style={{ fontFamily:"Medium", fontSize:12, color:"#9ca1a2" }}>2 mins ago</Text> </View> <View style={{width:"20%", alignItems:"flex-end"}}> <Icon name="sound-mix" color="#044244" size={20}/> </View> </View> {/* 横向滚动的同用户帖子列表 */} <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} pagingEnabled={true} style={{marginTop: 20, width: '100%'}} > {group.posts.map(post => ( <View key={post.id} style={{width: 300, marginRight: 15}}> <ImageBackground source={post.photo} style={{ width:"100%", height:220, }} imageStyle={{ borderRadius:30 }} > <View style={{ height:"100%", flexDirection:"row", alignItems:'flex-end', justifyContent:"flex-end" }}> <TouchableOpacity onPress={()=>this.props.navigation.navigate('Detail')} style={{ marginBottom:20, borderRadius:5, padding:5, backgroundColor:"#e8e8e8" }} > <Icon name="forward" color="#044244" size={20}/> </TouchableOpacity> <TouchableOpacity onPress={() => { // 修改对应post的liked状态即可,不要把点赞状态存在组件内部state const newGroups = [...this.state.postGroups] const targetGroup = newGroups.find(g => g.userId === group.userId) const targetPost = targetGroup.posts.find(p => p.id === post.id) targetPost.liked = !targetPost.liked this.setState({postGroups: newGroups}) }} style={{ marginBottom:20, borderRadius:5, padding:5, backgroundColor:"#e8e8e8", marginLeft:10, marginRight:20 }} > <Icon name={post.liked ? "heart" : "heart-outlined"} color={post.liked ? "red" : "#044244"} size={20} /> </TouchableOpacity> </View> </ImageBackground> </View> ))} </ScrollView> </View> ))}
注意事项
- 横向ScrollView的子项宽度可以自己调整,pagingEnabled属性开了之后滑动会自动对齐整页,体验更好
- 点赞状态要绑定到具体的post数据上,不要存在组件内部state,避免组件复用的时候状态混乱
- 你原来写的帖子旁边的装饰色块,可以直接加在横向ScrollView的同级位置,按你原来的样式写就行
内容的提问来源于stack exchange,提问作者Cole
相关产品推荐
相关产品推荐

