【问题标题】:How do I alternate colors in Flat List (React Native)如何在平面列表中交替颜色(React Native)
【发布时间】:2018-09-13 16:48:50
【问题描述】:

尝试在 React Natives Flatlist 中替换颜色。我相信我需要 rowID 或类似的东西来做到这一点。这是我到目前为止所得到的:

let colors = ['#123456', '#654321', '#fdecba', '#abcdef'];


<View >
    <FlatList style={{backgroundColor: colors[this.index % colors.length]}}

      data={this.state.dataSource}
      renderItem={({item}) => <Text style={styles.listStyle}>{item.title}, {item.releaseYear}</Text>}
      keyExtractor={(item, index) => index}
    />
  </View> 

有什么想法吗?

【问题讨论】:

    标签: javascript react-native react-native-flatlist


    【解决方案1】:

    renderItem 回调参数有一个属性index,允许您访问当前行的行索引:

    <View >
      <FlatList
        data={this.state.dataSource}
        keyExtractor={(item, index) => index}
        renderItem={({item, index}) => (
          <View style={{ backgroundColor: colors[index % colors.length] }}>
            <Text style={styles.listStyle}>{item.title}, {item.releaseYear}</Text>
          </View>
        )}
      />
    </View> 
    

    【讨论】:

    • 太棒了,谢谢!但是我如何实际使用它:&lt;FlatList style={{backgroundColor: ???} 应该是this.color 吗?
    • @johanjohansson 您没有将背景颜色提供给 FlatList,您将在 renderItem 回调中分别将其提供给每一行。我更新了代码示例以反映这一点
    • 如果您使用 react-native-element 的 ListItem 则使用:&lt;ListItem containerStyle = {{ backgroundColor: index % 2 == 0 ? "#f2f2f2" : "#FFFFFF" }} />
    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2022-08-08
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多