温馨提示:本文翻译自stackoverflow.com,查看原文请点击:reactjs - create an array to change color of one item at a time
react-native react-native-android reactjs

reactjs - 创建一个数组以一次更改一项的颜色

发布于 2020-04-14 10:25:51

我创建了一个like函数,该函数仅更改单个项目的颜色,并且根据其ID对该项目进行了设置,但是,当我喜欢第一个项目时,会传递相同的ID,但是所有图标也会变为红色,我该如何撤消呢?

我喜欢的功能如下:

onButtonPress = async(item) => {
    console.log(item)
    console.log(this.state.buttonColor,'hello')
    if(this.state.buttonColor='white'){
    try {
      const response = await fetch("some url"+item._id);
      const resJson = await response.text();
      this.setState({

        buttonColor:'red',

      }, console.log(resJson),
      console.log(this.state.buttonColor,'hi'));
    }
    catch (error) {
      console.error(error);
    }
  }

  };

我在平面列表中将此功能称为图标,我将在下面共享该图标的片段:

  <TouchableOpacity
                 onPress= {() => this.onButtonPress(item)}
                style={{
                  alignItems: 'center',

                  borderRadius: 60,
                  padding: 10,
                }}>
                <Icon
                  name="heart"
                  size={30}
                  color={this.state.buttonColor}

                />
              </TouchableOpacity>

可以,请告诉我您是否还有其他要求,并告诉我该怎么做?

查看更多

提问者
TRINA CHAUDHURI
被浏览
12
Alexander 2020-02-03 17:36

您需要将状态元素的ID存储为活动状态(红色)。

onButtonPress = async(item) => {
    if(!this.state.likedItemIds.includes(item._id)){
       try {
         const response = await fetch("some url"+item._id);
         const resJson = await response.text();
         this.setState(prevState => ({
           likedItemIds: [...prevState.likedItemIds, item._id]
         }))
       }
       catch (error) {
         console.error(error);
       }
    }
};

<TouchableOpacity
 onPress= {() => this.onButtonPress(item)}
  style={{
    alignItems: 'center',
    borderRadius: 60,
    padding: 10,
  }}>
  <Icon
    name="heart"
    size={30}
    color={state.likedItemIds.includes(item._id) ? "red" : "white"}
  />
</TouchableOpacity>