如何在 Flat List (React Native) 中交替颜色

How do I alternate colors in Flat List (React Native)

正在尝试更换 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> 

有什么想法吗?

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>