React Native 中的 ListView 网格 [英] ListView grid in React Native

查看:44
本文介绍了React Native 中的 ListView 网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 React Native 中构建一个简单的应用程序,该应用程序从远程 JSON 源获取列表并将它们显示在屏幕上.

到目前为止,在这里使用优秀的,以及 ListView 包装 ScrollView 的知识等等.考虑到这一点,您可以使用 ScrollView 的 contentContainerStyle 道具来设置项目的样式.

var TestCmp = React.createClass({getInitialState:函数(){var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});var data = Array.apply(null, {length: 20}).map(Number.call, Number);返回 {数据源:ds.cloneWithRows(data),};},渲染:函数(){返回 (<ListView contentContainerStyle={styles.list}数据源={this.state.dataSource}renderRow={(rowData) =><Text style={styles.item}>{rowData}</Text>}/>);}});

只是一个带有一些虚拟数据的 ListView.注意 contentContainerStyle 的使用.这是样式对象:

var 样式 = StyleSheet.create({列表: {flexDirection: '行',flexWrap: '包裹'},物品: {背景颜色:'红色',保证金:3,宽度:100}});

我们告诉容器我们想要包装行中的项目,然后我们设置每个子对象的宽度.

I'm building a simple app in React Native that fetches listings from a remote JSON source and displays them on screen.

So far, using the excellent example here, I've managed to get the results to display using the ListView components in rows (i.e. 1 result per row, see screenshot). I need the results to display in a grid, i.e. 3 to 6 items per row, depending on the screen size and orientation.

What is the best way to get these results into a grid? Can I use ListView for this, or is that only for one-per-row results? I've tried playing around with flexbox styles but, since React doesn't seem to accept % values and ListView doesn't accept styles, I haven't yet had any success.

解决方案

You need to use a combination of flexbox, and the knowledge that ListView wraps ScrollView and so takes on its properties. With that in mind you can use the ScrollView's contentContainerStyle prop to style the items.

var TestCmp = React.createClass({
    getInitialState: function() {
      var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      var data = Array.apply(null, {length: 20}).map(Number.call, Number);
      return {
        dataSource: ds.cloneWithRows(data),
      };
    },

    render: function() {
      return (
        <ListView contentContainerStyle={styles.list}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text style={styles.item}>{rowData}</Text>}
        />
      );
    }
});

Just a ListView with some dummy data. Note the use of contentContainerStyle. Here's the style object:

var styles = StyleSheet.create({
    list: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    item: {
        backgroundColor: 'red',
        margin: 3,
        width: 100
    }
});

We tell the container we want items in a wrapping row, and the we set the width of each child object.

这篇关于React Native 中的 ListView 网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆