【问题标题】:React Native Flatlist dynamic styleReact Native Flatlist 动态样式
【发布时间】:2019-07-17 00:50:52
【问题描述】:

我试图用反应原生 FlatList 项目制作按钮,这意味着当我点击它们时它们会改变颜色。 这是由 renderItem 属性渲染的函数:

renderRows(item, index) {
return (
  <TouchableOpacity
    key={index}
    style={[styles.item, this.calculatedSize()]}
    onPress={() => this.onPressImage(index)}
  >
    <Image
      style={[styles.picture]}
      source={{ uri: item.uri }}
    />
    <View
      style={[
        styles.imageTextContainer,
        {
          backgroundColor:
            _.indexOf(this.active, index) === -1
              ? 'rgba(0,0,0,0.2)'
              : 'rgba(26, 211, 132, 0.7)',
        },
      ]}
    >
      <Text style={styles.imageText}>{item.title}</Text>
    </View>
  </TouchableOpacity>
 )
}

哦,是的,我正在使用 loadash 来获取索引。 函数“onPressImage(索引)”工作正常,在“this.active”(数组)中我总是有我想改变颜色的元素的位置(整数), 但是什么也没发生,你唯一能看到的是 touchableOpacity 的响应。我做错了什么?

【问题讨论】:

  • 您正在影响某些东西的外观,您需要更新状态,因为这将触发重新渲染。因此,最好将活动值数组存储在 state 中。

标签: react-native react-native-flatlist


【解决方案1】:

就像Andrew 说的,你需要触发重新渲染,通常是通过更新状态。

但是,如果项目不依赖于 FlatList 之外的任何内容,我建议为项目本身创建一个组件(最好是 PureComponent),并在按下时更新它们的状态。这样,它只会在发生更改而不是父组件时单独重新渲染每个列表项。

【讨论】:

    【解决方案2】:

    谢谢,更新状态有点困难,我使用的 items 数组已在类组件之外声明,因此仅使用带有应在状态下更改颜色的索引的“活动”数组是不够的,我不得不像这样映射状态中的项目数组:

    state = {
      items: items.map(e => ({
        ...e,
        active: false,
      }))
    }
    

    然后我可以像这样操纵想要更改颜色的元素的活动状态:

    onPressItem(index) {
      const { items } = this.state
      const newItems = [...this.state.items]
      if (items[index].active) {
        newItems[index].active = false
      } else {
        newItems[index].active = true
      }
      this.setState({ items: newItems })
    }
    

    然后像这样改变颜色:

    style={{
      backgroundColor: item.active
        ? 'rgba(26, 211, 132, 0.7)'
        : 'rgba(0,0,0,0.2)',
    }}
    

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 2019-01-20
      • 2018-10-20
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多