如何在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但显然这不起作用。问你有什么好办法吗?

用括号表示法将它们包装起来,以使用计算属性,并在对象中包含所有*ItemSyle

const allStyles = {
healthItemStyle: {...},
...
}
<ListItem style={allStyles[`${scenarioHealth[index]}ItemStyle`]}>

这里只是一个沙盒的例子。

也许您可以将样式选项集中到一个对象中,然后在渲染<ListItem/>组件时动态选择这些选项,如下所示:

const allStyles = {
healthItemStyle : {
backgroundColor:'green'
},
warningItemStyle : {
backgroundColor:'yellow'
}, 
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)=>{
const styleKey = `${ item }ItemStyle`;
const style = allStyles[ styleKey ];
return(
<ListItem style={ style }>
<ListItemText primary={item} secondary={scenarioHealth[index]}/>
</ListItem>
)
});

你很接近。

请记住,React组件的style属性希望成为一个对象。

你在这里做什么:

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

只是将其设置为字符串。

相反,查找这样的对象地图:

const styles = {
health: {
backgroundColor:'green'
},
warning: {
backgroundColor: 'yellow'
}, 
error: {
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={styles[scenarioHealth[index]]}>
<ListItemText primary={item} secondary={scenarioHealth[index]}/>
</ListItem>
)
});

顺便说一句,你可能想看看react jss,它看起来很像你在这里做的事情。

${scenarioHealth[index]}ItemStyle为您提供了正确的字符串,但您需要访问变量所包含的值。

您可以更改变量的定义方式。例如,定义一个名为bgColors的对象,并将项目映射到其颜色:

const bgColors = {
healthItemStyle: 'green',
warningItemStyle: 'yellow',
errorItemStyle: 'red'
}

然后你可以访问这样的颜色:

bgColors[`${scenarioHealth[index]}ItemStyle`]

最新更新