4 回答
TA贡献1797条经验 获得超6个赞
您可以在三元运算符的帮助下做到这一点
render = () => {
const count_variable = this.get_count();
return (
<span>counter</span>
<span style={{ color: count_variable === 0 ? 'red' : count_variable === 1 ? 'blue' : 'green' }}>
{count_variable}
</span >
)
}
TA贡献1845条经验 获得超8个赞
你可以这样做:
render = () => {
const count_variable = this.get_count(); //this function returns an
//integer variable
let color = "";
switch(count_variable) {
case 0: color = "red"; break;
case 1: color = "blue"; break;
case 2: color = "green"; break;
// Add more cases here for more colors
}
return (
<div>
<span>counter</span>
<span style={{color: color}}>{count_variable}</span>
</div>
)
}
当您在一段时间后返回代码时,三元运算符可能会非常混乱,这就是我使用 switch 语句的原因。它将允许您稍后轻松添加更多案例,并在没有匹配项时提供默认案例。
TA贡献2011条经验 获得超2个赞
这应该对你有用,这是一个很好的阅读https://reactjs.org/docs/dom-elements.html
let divStyle = {
color: 'blue'
};
render = () => {
const count_variable = this.get_count(); //this function returns an
//integer variable
if (count_variable===0)
divStyle.color = 'red'
else if (count_variable===1)
divstyle.color = 'blue'
else
divstyle.color = 'green'
return (
<div>
<span>counter</span>
<span style={divStyle}>{count_variable}</span>
</div>
)
}
TA贡献1804条经验 获得超8个赞
render = () => {
const count = this.get_count(); //this function returns an
return (
<div>
<span>counter</span>
<span style={color: count === 0 ? 'red' : count === 1 ? 'blue' : 'green'}>{count}</span>
</div>
)
}
添加回答
举报