gpt4 book ai didi

javascript - 异步获取后将颜色更改为图标

转载 作者:行者123 更新时间:2023-11-29 23:46:00 25 4
gpt4 key购买 nike

我有一个 TouchableHighlight 的矢量图标。当按下 TouchableHighlight 时,应用程序将从 API 获取内容。解析结果后,将结果保存在一个state中,state名为favorited,是一个boolean数组,如果图标被按下则保存。

我的想法是将 ID 是否被收藏保存到一个名为“收藏”的 bool 数组中。所以颜色的状态就是this.state.favorited[id]。以这种方式设置颜色可能是个坏主意,希望你能给我更好的主意:)

vector-icon中的color参数是

<Ionicons.Button 
name="ios-star"
color={ (this.state.favorited[post.id]) ? 'white' : 'black' }
backgroundColor="transparent"
underlayColor="transparent"
onPress={()=> {
vote = this.favPost(post);
}
}
/>

所以我的尝试是当按下图标时,将数据发送到 API 并在获取的异步响应中,然后更新状态 this.state.favorited[data.id]

favPost 函数更新状态“已收藏”:val是真还是假

favPost(data){
fetch(..blabla..).
then(response.json()).
then({
...
var favorited = this.state.favorited;
favorited[post.id] = val;
this.setState({'favorited' : favorited});
...
})
}

所以我不知道该怎么做。也许我不能使用 (bool) 分配颜色? : 表达式。


react-native --version:

react-native-cli: 2.0.1
react-native: 0.43.3

npm 列表 --depth=0 | grep 矢量图标

├── react-native-vector-icons@4.1.1

最佳答案

您的方向是正确的,但您的代码中存在一些错误。

1º 你不能改变状态 directly

var favorited = this.state.favorited;
favorited[post.id] = val; // This is wrong

假设您将收藏的 id 存储在这样的状态中

state = {
favorited : [] // [1,2,3, etc]
}

你应该像这样更新你的状态

favPost(data){
fetch(..blabla..).
then(response.json()).
then({
...
this.setState({favorited: [...this.state.favorited, post.id]});
...
})
}

2º 你用来检查按钮是否被点击的条件应该是这样的

color={this.state.favorited.find(v => v === post.id) ? 'white' : 'black' }

Here's a working example您正在努力实现的目标。

(您只需要删除模式并点击“点击播放”)。

关于javascript - 异步获取后将颜色更改为图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44122837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com