Zai*_*shi 5 javascript arrays react-native
我想在按下心脏图标将其更改为红色时更新数组对象中关键心脏的状态,为此,我正在使用react native图标,并且在单击时使用heart和hearto进行切换
这是代码:
state = {
localAdversiment: [
{
title: "Ecloninear 871",
image: require("../../assets/images/truck_image.png"),
year: "2015",
type: "Truck",
status: "new",
price: "$ 2000",
heart: "hearto"
}
Run Code Online (Sandbox Code Playgroud)
按下心脏图标时调用的功能
handleFavourite = index => {
const { heart } = this.state.localAdversiment[index];
this.setState(
{
heart: "heart"
}
);
};
Run Code Online (Sandbox Code Playgroud)
这是心脏图标代码
<TouchableOpacity onPress={() => this.handleFavourite(index)}>
<Icon
name={item.heart}
type={"AntDesign"}
style={{ fontSize: 18 }}
/>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)
请帮助我如何在单击时将心脏更新为心脏而不是心脏
您可以按照以下方法轻松完成此操作
state = {
localAdversiment: [
{
id: 0,
title: "Ecloninear 871",
image: require("../../assets/images/truck_image.png"),
year: "2015",
type: "Truck",
status: "new",
price: "$ 2000",
heart: "hearto",
selected: false
}
}
Run Code Online (Sandbox Code Playgroud)
现在在onPress上执行此操作
handleFavourite = (item) => {
const { id } = item;
this.setState({
localAdvertisement: this.state.localAdvertisement.map((item) => {
if(item.id === id){
return {
...item,
selected: !item.selected
}
}
return item
})
})
};
Run Code Online (Sandbox Code Playgroud)
现在像这样渲染
<TouchableOpacity onPress={() => this.handleFavourite(item)}>
<Icon
name={item.selected ? "heart" : 'hearto'}
type={"AntDesign"}
style={{ fontSize: 18 }}
/>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)
希望对您有帮助
归档时间: |
|
查看次数: |
56 次 |
最近记录: |