简体   繁体   中英

React use object value as state variable name

I want to use the value of one object to access state variable name

for ex:

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>
)
} 

The state variables are: this.state.data.name and this.state.data.email. How to replace the obj.name here

If i give {this.state.data.obj.name} it's throwing an error like name not found

When using variables for keys, you need to use square brackets

this.state.data[obj.name]

In square brackets notation, your solution requests:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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