flatlist 将来自 json api 的数据渲染为每行 3 个项目

And*_*oud 5 react-native react-native-flatlist

大家好,我正在从 json api 获取数据,我正在使用 flatlist 来呈现项目。我正在使用numColumns属性每行显示 3 个项目,但假设我有 7 或 8 个项目,但在渲染时遇到问题。我想显示的布局是这样的

X X X
X X X
X X
Run Code Online (Sandbox Code Playgroud)

但我得到的是: 布局

这是我的代码:

    _renderItem = ({ item, index }) => (
            <View style={categorystyles.Category} key={index}>
                <TouchableOpacity activeOpacity={.5}
                    onPress={() => this.props.navigation.navigate('ListingPerCategory', { catid: item.id })}>
                    {item.category_app_icon ? <Image style={categorystyles.CategoryImg}
                        source={{ uri: `${item.category_app_icon}` }} /> :
                        <Image style={categorystyles.CategoryImg}
                            source={require('../assets/coffeecup.png')} />}
                </TouchableOpacity>
                <Text style={{ marginTop: 5 }}>{escape(item.name).replace('%20', ' ').replace('%26amp%3B%20', ' ')}</Text>
            </View>
        )
   render(){
     return(
        <FlatList
        horizontal={false}
        data={this.state.categories}
        keyExtractor={(item, index) => item.id}
        numColumns={3}
        renderItem={this._renderItem}
    />
     )
   }

    const styles = StyleSheet.create({
       Category: {
            flex:1,
            justifyContent: 'center',
            alignItems:'center',    
            margin:5
        },
        CategoryImg: {
            resizeMode: 'contain',
            width: 50,
            height: 50
        }
    })
Run Code Online (Sandbox Code Playgroud)

Pri*_*dya 2

由于您使用的是flex: 1and alignItems: center,您的布局将如下所示后像

因此,内部将根据项目布局垂直水平items居中对齐。

相反,您需要检查width设备的并基于此添加布局。

按照您的风格

Category: {
  flex:1,
  maxWidth: Dimensions.get('window').width / 3 - 10, // Width / 3 - (marginLeft and marginRight for the components)
  justifyContent: 'center',
  alignItems:'center',    
  margin:5
},
Run Code Online (Sandbox Code Playgroud)

添加此样式后,布局将如下所示 后像