如何在FlatList的当前头像图片上仅添加“cover”文本标识
问题原因
你代码的核心问题是renderItem的语法逻辑错误:
- 条件判断写在了
renderItem函数体外部,该部分逻辑不会被执行 - 错误使用整个
photos数组和profilePictureURL做匹配,应该匹配当前遍历到的单个图片资源item
修正方案
你需要在非添加按钮的图片渲染逻辑里,新增条件判断:如果当前item和profilePictureURL相等,就叠加显示cover标识,给标识加绝对定位样式固定在图片上方即可。
修正后的代码如下:
const { firstName, lastName, profilePictureURL } = currentUser; const userLastName = currentUser && lastName ? lastName : ' '; const userfirstName = currentUser && firstName ? firstName : ' '; {myphotos.map((photos, i) => ( <View key={'photos' + i} style={styles.slide}> <View style={styles.slideActivity}> <FlatList horizontal={false} numColumns={2} data={photos} scrollEnabled={true} renderItem={({ item, index }) => item.add ? ( <TouchableOpacity key={'item' + index} style={[ styles.myphotosItemView, { borderWidth: 1, borderColor: '#5DD6FF', }, ]} onPress={onSelectAddPhoto}> <Icon style={styles.icon} name="add" size={40} color="#5DD6FF" /> </TouchableOpacity> ) : ( <TouchableOpacity key={'item' + index} style={styles.myphotosItemView} onPress={() => onSelectDelPhoto(i * 6 + index) }> <FastImage style={{ width: '100%', height: '100%' }} source={{ uri: item }} /> {/* 匹配当前头像时显示cover标识 */} {item === profilePictureURL && ( <Text style={styles.coverTag}>Couverture</Text> )} </TouchableOpacity> ) } /> </View> </View> ))}
样式补充
你需要新增coverTag样式,设置绝对定位将标识固定在图片的合适位置:
const styles = StyleSheet.create({ // 原有样式保持不变 coverTag: { position: 'absolute', top: 4, right: 4, backgroundColor: 'rgba(0,0,0,0.6)', color: '#ffffff', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4, fontSize: 12 } })
切换头像后只要更新currentUser.profilePictureURL的取值,FlatList会自动重渲染,cover标识会自动同步到新选中的头像上。
内容的提问来源于stack exchange,提问作者Xwingoga06
相关产品推荐
相关产品推荐

