Reactjs 在平面列表中显示图像
我试图使用Reactjs 在平面列表中显示图像,reactjs,react-native,react-native-flatlist,Reactjs,React Native,React Native Flatlist,我试图使用FlatList在网格视图中渲染图像,但遇到了下一个问题: 我的代码片段: ... renderItem = ({item}) => { return ( <Image source = {{uri: item.photoUrl[0].photoUrl}} style = {{margin: 1, heigh
FlatList
在网格视图中渲染图像,但遇到了下一个问题:
我的代码片段:
...
renderItem = ({item}) => {
return (
<Image source = {{uri: item.photoUrl[0].photoUrl}} style = {{margin: 1,
height: Dimensions.get('window').width / 3,
width: Dimensions.get('window').width / 3,
resizeMode: 'cover'}}
/>
)
}
render() {
if(this.props.viewOption === 'grid') {
return <FlatList
data = {this.state.photosKeysArray}
keyExtractor={(item, index) => item.id}
numColumns = {3}
renderItem={this.renderItem}
/>
} ...
。。。
renderItem=({item})=>{
返回(
)
}
render(){
如果(this.props.viewOption=='grid'){
返回项.id}
numColumns={3}
renderItem={this.renderItem}
/>
} ...
问题是平面列表应该根据numColumns
自行计算项的宽度,对吗?所以在图像中
我应该只指定高度。因为我想渲染方形图像,所以我给高度指定了一个值,该值等于Dimensions.get('window').width/3
,其中3
是numColumns
的值
之后,FlatList将渲染空白而不是图像
如果我将width
属性添加到Image
(就像在我的代码片段中一样)并将其定义为高度(方形图像,记得吗?),那么FlatList将使用方形图像渲染3列,但它们的显示方式与我的草图上的相同(两个完整图像,最后一列被剪切):
如何显示三个完整列?numColumns
只能使用horizontal={false}呈现多个列
<FlatList
numColumns={3}
data={this.state.data}
renderItem={({ item }) => this.renderItem(item)}
/>
this.renderItem(项目)}
/>
renderItem
根据要求设置项目(柔性/宽度/高度)
renderItem(item) {
return (
<TouchableOpacity>
<View style={{
width: (Constant.SCREEN.width - 32) / 3,
height: (Constant.SCREEN.width - 32) / 3,
justifyContent: 'center'
}}>
<Image style={{ width: '70%', height: '70%', alignSelf: 'center' }} resizeMode='contain' source={{ uri: item.image }}></Image>
<SPText
style={{ flex: 1.0, textAlign: 'center', marginLeft: 4, marginRight: 4 }}
text={item.text}
fontSize={10}
textColor='white' />
</View>
</TouchableOpacity>
)
}
renderItem(项目){
返回(
)
}
使用图像的宽度和高度的下一个值解决了问题:
height: (Dimensions.get('window').width - (30 + 2*this.state.columns)) / this.state.columns,
width: (Dimensions.get('window').width - (30 + 2*this.state.columns)) / this.state.columns,
其中,30
是主屏幕的双(左和右)边距,2
是图像的双边距。您想要简单的正方形吗,那么你应该知道react native的这个属性,它叫做,你只需设置宽度或高度,在样式中将纵横比设置为1,你就有了一个正方形
这是不变的
<FlatList
numColumns={3}
data={this.state.data}
renderItem={({ item }) => this.renderItem(item)}
/>
this.renderItem(项目)}
/>
但这更简单
renderItem(item) {
return (
<TouchableOpacity
style={{flex:1/3, //here you can use flex:1 also
aspectRatio:1}}>
<Image style={{flex: 1}} resizeMode='cover' source={{ uri: item.photoUrl[0].photoUrl}}></Image>
</TouchableOpacity>
)
}
renderItem(项目){
返回(
)
}
需要注意的是,如果您在所有行下面都有一个额外的项,并且您使用flex:1而不是flex:1/3,那么它将是一个非常大的正方形,因为您可以使用所描述的方法在图像组件上使用宽度属性“33%”可能更好哦!伙计们,投票给这个答案。AspectRatio是一条路要走。非常感谢@ValdaXD!这么聪明的解决方案,谢谢!