繁体   English   中英

React使用对象值作为状态变量名称

[英]React use object value as state variable name

我想使用一个对象的值访问状态变量名称

例如:

const displayName = [
    {
        name: 'name', //Actually this is the state variable name 
        displayText: 'Name: '
    },
    {
        name: 'email',
        displayText: 'E-mail ID: '
    }
]

{
displayName.map(obj =>  (
    <p>{obj.displayText}</p>
    <div>
        {this.state.data.obj.name} //Here am facing issue. The state variables are: this.state.data.name and this.state.data.email. How to replace the obj.name here
    </div>
)
} 

状态变量是:this.state.data.name和this.state.data.email。 如何在这里替换obj.name

如果我给{this.state.data.obj.name}它会抛出一个错误,例如name not found

使用键变量时,需要使用方括号

this.state.data[obj.name]

在方括号中,您的解决方案要求:

this.state['data']['obj']['name']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM