const healthItemStyle={
backgroundColor:'green'
};
const warningItemStyle={
backgroundColor:'yellow'
};
const errorItemStyle={
backgroundColor:'red'
};
const scenario = ['AppPulse Active','AppPulse Mobile','AppPulse Trace','BSM-Login','Service Portal'];
const scenarioHealth = ['health','warning','health','health','error'];
const items=scenario.map((item,index)=>{
return(
<ListItem style={`${scenarioHealth[index]}ItemStyle`}>
<ListItemText primary={item} secondary={scenarioHealth[index]}/>
</ListItem>
)
});
如上面的代码所示,我希望能够动态生成标签样式属性的变量名。
我已经尝试了很多,例如 ${scenarioHealth[index]}ItemStyle
但显然这是行不通的。那请问大家有什么好的办法吗?
最佳答案
用方括号括起来以使用 computed property并将所有 *ItemSyle
包含在对象中:
const allStyles = {
healthItemStyle: {...},
...
}
<ListItem style={allStyles[`${scenarioHealth[index]}ItemStyle`]}>
这只是一个example sandbox .
关于javascript - 如何在react.js中向变量名添加另一个变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53605693/