如何在平面列表中替换颜色(React Native)

时间:2018-04-04 07:57:16

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

尝试在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> 

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

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>