中心对齐原生的ListView内容

Nim*_*nya 5 css listview ios react-native

我使用ListView列出了一些项目,但它们都是左对齐的.如何中心对齐它们而不使用另一个视图包装ListView?

ListView的代码

<ListView
   dataSource={this.state.dataSource}
   renderRow={this.renderItem}
   style={styles.listView}
/>
Run Code Online (Sandbox Code Playgroud)

ListView样式

listView: {
   paddingTop: 20,
   paddingBottom: 20,
}
Run Code Online (Sandbox Code Playgroud)

这该怎么做?提前致谢.

Joh*_*ley 17

你可以通过使用contentContainerStyleListView prop将所需的flexbox样式直接应用到ListView的内部容器来解决这个问题,如下所示:

<ListView
  dataSource={this.state.dataSource}
  renderRow={this.renderItem}
  contentContainerStyle={styles.listView}
/>

// ...    

var styles = StyleSheet.create({
   listView: {
     flex: 1,
     justifyContent: 'center',
   },
});
Run Code Online (Sandbox Code Playgroud)

同样,当您需要通过添加样式alignItems: 'center'来使两个轴居中时,这也适用listView.


eya*_*l83 5

this.renderItem 应该是一个呈现行的函数。您的行应该设置它需要的样式。所以像这样:

<ListView
  dataSource={this.state.dataSource}
  renderRow={this.renderItem}
  style={styles.listView}
/>

renderItem: (item) {
  <ItemRow item={item} />
}
Run Code Online (Sandbox Code Playgroud)

然后在 ItemRow 组件中:

render: () {
  <View style={flexDirection: 'row', justifyContent: 'center'}>
    <Text>{this.props.item.name</Text>
  </View>
}
Run Code Online (Sandbox Code Playgroud)