当前位置: 代码迷 >> JavaScript >> React使用对象值作为状态变量名称
  详细解决方案

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

热度:19   发布时间:2023-06-06 09:34:30.0

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

例如:

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']
  相关解决方案