在本机中一次水平滚动两行

时间:2018-09-27 09:55:46

标签: react-native

我有一个水平scrollView,其中有2行以水平单位滑动。以下是工作的测试代码,但是相同的数据被渲染两次。即。第一列的两行中的“ post 1”和第二列的两行中的“ post 2”。我需要的是第一列中的“ post 1”和“ post 2”,第二列中的“ post 3”和“ post 4”,依此类推。类似于表格布局,在水平滚动视图中具有2行和几列。

https://snack.expo.io/@codebyte99/multipleloop

renderRow(item) {
    return (
      <View style={{ margin: 5 }}>   
        <View style={{
            backgroundColor: 'red',
            width: 200,
            height: 100,
            marginBottom: 1,
          }}>
          <Text>{item.title}</Text>
        </View> 

        <View
          style={{
            backgroundColor: 'green',
            width: 200,
            height: 100,
            marginBottom: 1,
          }}>
          <Text>{item.title}</Text>
        </View>
      </View>
    );
}

render() {
    return (
      <View style={styles.container}>
        <ScrollView horizontal={true}>
          {this.state.data.map(item => this.renderRow(item))}
        </ScrollView>
      </View>
    );
}

enter image description here

1 个答案:

答案 0 :(得分:0)

将数组拆分为大小为2的多个数组,如下所示

var arrays = [], size = 2;
while (this.state.data.length > 0)
    arrays.push(this.state.data.splice(0, size));

FlatListhorizontal={true}属性一起使用

<FlatList data={arrays}
          horizontal={true}
          renderItem={({ item, index }) => this.renderRow(item)} />

和您的renderRow看起来像这样

renderRow(item) {
    return (
        <View style={{ margin: 5 }}>
            <View style={{
                backgroundColor: 'red',
                width: 200,
                height: 100,
                marginBottom: 1,
            }}>
                <Text>{item[0].title}</Text>
            </View>
            {item.length > 1 ?
                <View
                    style={{
                        backgroundColor: 'green',
                        width: 200,
                        height: 100,
                        marginBottom: 1,
                    }}>
                    <Text>{item[1].title}</Text>
                </View> : null}
        </View>
    );
}