首页 > 解决方案 > 为交替背景创建循环或播放状态

问题描述

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

为此,我想使用它:

背景颜色:item.id % 2 === 0 ?'#fde3a7' : '#FFF'

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

屏幕截图

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

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

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

列表的整个代码:

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>
);

标签: javascriptlistreact-nativebackground-coloralternate

解决方案


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

renderItem({ item, index, separators });

通过索引扩展您的 renderItem 方法并通过道具将索引传递给 ListItem


推荐阅读