创建循环或播放交替背景的状态

问题描述

我有一个列表,我想更改列表中项目的背景颜色。 基本上,为了增加对比度并获得更好的渲染效果,我想将背景从两个产品中的一个更改为两个。

为此,我想使用它:

backgroundColor: item.id % 2 === 0 ? '#fde3a7':'#FFF'

它有效,但问题是我的 ID 不一定是有序的,所以它给了我:

screencap

但是,我不知道如何将其应用于二分之一的产品。 我的想法是将一个变量作为参数传递,该变量随每个循环递增或使用状态,例如,在每个位置,背景都会发生变化(例如偶数位置:白色背景,奇数位置背景橙色)

另一方面,我有这个想法,但我对如何实现它有点迷茫。

我不知道我是否表达得很好,你是否理解我的问题。无论如何,感谢您提供的任何帮助。

列表的全部代码

const Item = ({ item,onPress,style }) => (
  <ListItem
    style={{width:'100%'}}
    containerStyle= {{backgroundColor: item.id % 2 === 0 ? '#fde3a7' : '#FFF'}}
    bottomDivider
    onPress={() => this.props.navigation.navigate('ProductDetails',{productId:parseInt(item.id)})}>
    <ListItem.Content style={{flexDirection: 'row',justifyContent: 'space-between'}}>
      <Image //source={{uri: URL + item.photo.["_1_"].url}} style={{ width: 25,height: 25}}
      />
      <ListItem.Title style={{width: '65%',fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0,20) + ' ...'  :  item.name}</ListItem.Title>
      <ListItem.Subtitle style={{ color: '#F78400',position: "absolute",bottom: 0,right: 0 }}>{item.cost}{i18n.t("products.money")}</ListItem.Subtitle>
    </ListItem.Content>
  </ListItem>
);

解决方法

您可以使用从 renderItem 方法 (FlatList) 获得的索引参数而不是 item.id

renderItem({ item,index,separators });

通过索引扩展你的 renderItem 方法,并通过 props 将索引传递给 ListItem

,

我希望你有一系列的物品。您应该检查项目 index