[英]How do I change inline CSS styles using a variable in JSX inside a map function?
好的,所以我有一个map函数,该函数正在数组中运行并在DOM上为数组中的每个项目(“ colorItem”)创建div。 该数组是一个颜色数组,该数组中的每个项目都是颜色的十六进制值(例如: #1a703f
)。
我正在尝试更改每个div项目的背景,以使其与数组中的项目匹配。 但是,因为我无法访问内联CSS JSX内map函数内的变量。
{this.state.colorsArray.map(colorItem =>
<div className="m-4">
<div className="max-w-sm rounded overflow-hidden shadow-lg w-48">
<div style={{ backgroundColor: {colorItem} }} className="h-32">
</div>
<div className="px-6 py-4">
<p className="text-grey-darker">
{colorItem}
</p>
</div>
</div>
</div>
`
这样的事情可能适合您:
{this.state.colorsArray.map(colorItem => {
let colorstyle = {
backgroundColor: colorItem
}
return (
<div className="m-4">
<div className="max-w-sm rounded overflow-hidden shadow-lg w-48">
<div style={colorstyle} className="h-32">
</div>
<div className="px-6 py-4">
<p className="text-grey-darker">
{colorItem}
</p>
</div>
</div>
</div>
})}
如果在lambda'backgroundColor'中调用参数,则可以使用此对象的短符号:
{this.state.colorsArray.map(backgroundColor =>
<div className="m-4">
<div className="max-w-sm rounded overflow-hidden shadow-lg w-48">
<div style={{ backgroundColor }} className="h-32">
</div>
<div className="px-6 py-4">
<p className="text-grey-darker">
{backgroundColor}
</p>
</div>
</div>
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.