【问题标题】:Horizontal scroll two rows at once in react native在本机反应中一次水平滚动两行
【发布时间】:2018-09-27 09:55:45
【问题描述】:

我有一个水平滚动视图,其中有 2 行作为一个单元水平滑动。以下是它工作的测试代码,但相同的数据被渲染了两次。 IE。在第一列的两行中“发布 1”和在第二列的两行中发布 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>
    );
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    将您的数组拆分为多个大小为 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>
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2021-08-12
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      相关资源
      最近更新 更多