我创建了一个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>
可以,请告诉我您是否还有其他要求,并告诉我该怎么做?
您需要将状态元素的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>