在react native中的列表视图中并排渲染两个项目(图像) [英] Render two items (images) side by side in a list view in react native

查看:283
本文介绍了在react native中的列表视图中并排渲染两个项目(图像)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在react native中设计类似于以下屏幕截图的内容. 请注意,每个图块都是从后端获取的Product元素.

I'm trying to design something like the below screenshot in react native. Please note each tile is a Product element fetched from the backend.

但是我无法使用ListView及其renderRow方法来执行此操作,这使我无法使用任何类型的InfiniteScroll组件.

But I'm unable to do this using a ListView and its renderRow method which is denying me to use any kind of InfiniteScroll Components.

当前,我一次运行一个包含2个元素的循环,并在滚动视图中渲染2个元素.下面是我的代码,可以更好地解释.

Currently I'm running a loop with 2 elements at a time and rendering 2 elements inside a scroll view. Below is my Code to explain better.

render() {
    var elem = [];
    for(var i = 0; i < this.state.products.length; i+=2) {
      var prod = this.state.products[i];
      var prod2 = this.state.products[i + 1];
      elem.push(
        <View style={styles.view} key={i} >
          <ProductTile onPressAction={this._pdpPage} prod={prod} index={i} />
          <ProductTile onPressAction={this._pdpPage} prod={prod2} index={i + 1} />
        </View>
      );
    }
    return (
        <ScrollView>
          {elem}
        </ScrollView>
    )
}

然后基于索引属性,我将元素左对齐或右对齐. 我的视图样式如下所示:

And then based on the index prop I'm aligning the elements on left or right. My View style looks like below:

view: {
  flex: 1,
  flexDirection: 'row',
},

请提出一种更好的方法.

Please suggest a better way to do this.

谢谢.

推荐答案

我们过去在生产环境中完成此操作的一种好方法是取得容器的宽度并设置容器的宽度,效果很好.卡片的宽度的50%,那么您只需将所有单个元素推入列表视图即可.另外,请确保将flexWrap设置为wrap.

A good way we have done this in production in the past, and it has worked out well, is to get the width of the container and set the width of the cards to 50% of the width, then you can just push all of the single elements into the listview. Also, be sure to set up a flexWrap of wrap.

这将适用于所有设备尺寸,并且不需要其他模块或库.

This will work across all device sizes, and requires not additional modules or libraries.

在下面查看示例代码,并在此处示例:

Check out the sample code below and example here:

https://rnplay.org/apps/t_6-Ag

/* Get width of window */
const width = Dimensions.get('window').width

/* ListView */
<ListView
  contentContainerStyle={styles.listView}
  dataSource={this.state.dataSource}
  renderRow={this.renderRow.bind(this)}
/>

/* Row */
renderRow () {
  return <View style={styles.card}>
           <Text>{rowData.name} {rowData.price}</Text>
         </View>

/* Styles */
listView: {
  flexDirection: 'row',
  flexWrap: 'wrap'
},
card: {
  backgroundColor: 'red',
  width: (width / 2) - 15,
  height: 300,
  marginLeft: 10,
  marginTop: 10
} 

这篇关于在react native中的列表视图中并排渲染两个项目(图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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