最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I alternate colors in Flat List (React Native) - Stack Overflow

programmeradmin2浏览0评论

Trying to alternate colors in React Natives Flatlist. I believe I need rowID or something similar to do it. This is what I've got so far:

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> 

Any ideas?

Trying to alternate colors in React Natives Flatlist. I believe I need rowID or something similar to do it. This is what I've got so far:

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> 

Any ideas?

Share Improve this question asked Apr 4, 2018 at 7:57 johanjohanssonjohanjohansson 5413 gold badges10 silver badges19 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 23

The renderItem callback argument has a property index that allows you to access the row index for the current row:

<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> 
发布评论

评论列表(0)

  1. 暂无评论