在视图中居中网格

时间:2017-10-24 07:54:31

标签: reactjs react-native flexbox

我正在用ListView创建一个网格。这是我的代码

export default class CategoryContainer2 extends Component {
  constructor() {
    super();
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['row 1', 'row 2','row 3','row 4','row 5']),
    };
  }

  render() {
    return (
      <View style={{         
        backgroundColor:'#ebeef0',
        alignItems:'center',
        justifyContent:'center'}}>
      <ListView contentContainerStyle={styles.list}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text style={styles.item}>{rowData}</Text>}
        />
        </View>
    );
  }
}

这是结果

enter image description here

正如您在我的代码中看到的那样,我正在尝试将网格置于屏幕中心,但这不起作用。你对如何做到了吗?

修改

如果网格上只有一行而不是视图居中

enter image description here

如果我增加项目的大小并且网格包含多行,则中心剂量不再起作用

enter image description here

修改

这是问题的snack

1 个答案:

答案 0 :(得分:6)

我认为问题是由ListView宽度与容器View宽度相同引起的。我有两个关于如何实现理想行为的想法。

对于这两个想法,我将paddingLeftpaddingRight添加到容器View,以ListView为中心。

首先想法是设置ListView样式justifyContent: 'space-between'justifyContent: 'space-around'。此选项允许一行中具有不同大小的项目,并且每行将包含它可以容纳的最多项目。但是,当行未满时,此选项会使第二行项目之间的边距不同。

第二个想法是计算项目的width,然后在每行中设置固定数量的项目。此选项更受控制,但需要修复项目的宽度。

我添加了一个2种不同方法的屏幕,here是示例应用程序的小吃

screen of 2 options

相关问题