这是您尝试的更新 jsfiddle:https://jsfiddle.net/fyLab6zr/21/
不确定这是否正是您想要的,但颜色是在 css 中指定的,因此应该给出特定颜色的 id 列表,以及所有不匹配的默认颜色:
.background {
background: red;
}
.background-1, .background-2 {
background: blue;
}
.background-3, .background-4 {
background: green;
}
然后你有一个 ids 列表,你可以遍历它来填充特定的 ids 行。
传入background-${id}中的id,设置className等于对应的id。如果存在,它将被设置样式,或者使用后备“背景”类
const Main = () => {
const ids= [1,1,3,2,1,3,4,5, 6, 1]
return (
<React.Fragment>
{ids.map((id) => {
return <div id={id} className={`background background-${id}`}>{id}</div>
})}
</React.Fragment>
)
}
ReactDOM.render(<Main />, document.querySelector("#app"))
编辑:
这种方法会创建您预定义的 id 列表,在本例中是两个列表,导致两种不同的颜色。如果没有匹配,它仍然默认返回background。 getColor 函数根据 id 给出正确的 className。您还可以根据需要预定义任意数量的元素。
const color1 = [1,2]
const color2 = [3,4]
const getColor = (id) => {
return color1.includes(id) ? 1 : color2.includes(id) ? 2 : -1
}
return (
<React.Fragment>
<div id="1" className={`background background-${getColor(1)}`}>1</div>
<div id="2" className={`background background-${getColor(2)}`}>2</div>
<div id="3" className={`background background-${getColor(3)}`}>3</div>
<div id="4" className={`background background-${getColor(4)}`}>4</div>
<div id="5" className={`background background-${getColor(5)}`}>5</div>
</React.Fragment>
)
}
ReactDOM.render(<Main />, document.querySelector("#app"))