首页 > 解决方案 > 如何在 react.js 中为变量名添加另一个变量值

问题描述

    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 但显然这不起作用。那请问有什么好的方法吗?

标签: javascriptreactjs

解决方案


用括号表示法将它们包装起来以使用计算属性并拥有所有*ItemSylein 对象:

const allStyles = {
  healthItemStyle: {...},
  ...
}

<ListItem style={allStyles[`${scenarioHealth[index]}ItemStyle`]}>

这里只是一个示例沙箱


推荐阅读