添加动态键设置状态,反应
我有这个状态,
this.state = {
dropdown1: false,
dropdown2: false,
dropdown3: false
}
我想使用 this.setState 访问这些状态下的下拉列表,但“dropdown”后面的数字来自 API,
onMaca = (ev) => {
this.setState({
dropdown + ev: true
})
}
所以我希望密钥是动态的“dropdown1”。
感谢您的回答
I have this state
this.state = {
dropdown1: false,
dropdown2: false,
dropdown3: false
}
I want to access to these dropdowns in state using this.setState but the number after 'dropdown' comes from API
onMaca = (ev) => {
this.setState({
dropdown + ev: true
})
}
So I want the key to be dynamic 'dropdown1' for example.
Thanks for your answers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以像这样访问对象属性 object['property name']
you can access the object property like this object['property name']
https://codezup.com/add-dynamic-key -to-object-property-in-javascript/
您可以使用其中任何一个来动态设置密钥。我将尝试用 setState 的示例来更新答案。
https://codezup.com/add-dynamic-key-to-object-property-in-javascript/
You can use any of these to set key dynamically. I will try to update the answer with an example in a while for setState.
状态是一个 JS 对象,因此您可以像平常一样获取它的键,如下所示:
现在您有一个数组:
[ "dropdown1", "dropdown1", "dropdown1" ]
使用它的一种方法是:
keysMap 看起来像这样:
[ { key: 'dropdown1', idx: 0, number "1" }, { key: 'dropdown1', idx: 1, number "2" }, { key: 'dropdown1', idx: 2, number "3" } ]
您可以查询
keysMap
以获得给定的dropDownNumber
,如下所示:要设置下拉列表的状态:
The state is a JS object, so you can get its keys as usual, like so:
Now you have an array:
[ "dropdown1", "dropdown1", "dropdown1" ]
One way to use it would be:
keysMap will look like so:
[ { key: 'dropdown1', idx: 0, number "1" }, { key: 'dropdown1', idx: 1, number "2" }, { key: 'dropdown1', idx: 2, number "3" } ]
You can query
keysMap
for a givendropDownNumber
like so:To set the dropdown's state: