如何使用 react 或 javascript 根据其内容向 span 标签添加不同的样式?

我有一个像下面这样的 span 元素,我想根据它的值更改 count_variable 颜色。


render = () => {

    const count_variable = this.get_count(); //this function returns an 

    //integer variable

    return (

        <div>

            <span>counter</span>

            <span>{count_variable}</span>

        </div>

    )

}

例如,输出如下所示,count 0


现在当这个 count_variable


value is 0 i want its color to be red

value is 1 want its color to be blue

value is greater than 1 its color to be green

我该怎么做。有人可以帮我解决这个问题。谢谢。


MM们
浏览 291回答 4
4回答

FFIVE

您可以在三元运算符的帮助下做到这一点render = () => {&nbsp; &nbsp; const count_variable = this.get_count();&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <span>counter</span>&nbsp; &nbsp; &nbsp; <span style={{ color: count_variable === 0 ? 'red' : count_variable === 1 ? 'blue' : 'green' }}>&nbsp; &nbsp; &nbsp; &nbsp; {count_variable}&nbsp; &nbsp; &nbsp; </span >&nbsp;)&nbsp; &nbsp;&nbsp;}

精慕HU

你可以这样做:render = () => {&nbsp; &nbsp; const count_variable = this.get_count(); //this function returns an&nbsp; &nbsp; //integer variable&nbsp; &nbsp; let color = "";&nbsp; &nbsp; switch(count_variable) {&nbsp; &nbsp; &nbsp; &nbsp; case 0: color = "red"; break;&nbsp; &nbsp; &nbsp; &nbsp; case 1: color = "blue"; break;&nbsp; &nbsp; &nbsp; &nbsp; case 2: color = "green"; break;&nbsp; &nbsp; &nbsp; &nbsp; // Add more cases here for more colors&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>counter</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style={{color: color}}>{count_variable}</span>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}当您在一段时间后返回代码时,三元运算符可能会非常混乱,这就是我使用 switch 语句的原因。它将允许您稍后轻松添加更多案例,并在没有匹配项时提供默认案例。

森林海

这应该对你有用,这是一个很好的阅读https://reactjs.org/docs/dom-elements.htmllet divStyle = {&nbsp; color: 'blue'};render = () => {&nbsp; &nbsp; const count_variable = this.get_count(); //this function returns an&nbsp;&nbsp; &nbsp; //integer variable&nbsp; &nbsp; if (count_variable===0)&nbsp; &nbsp; &nbsp; &nbsp; divStyle.color = 'red'&nbsp; &nbsp; else if (count_variable===1)&nbsp; &nbsp; &nbsp; &nbsp; divstyle.color = 'blue'&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; divstyle.color = 'green'&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>counter</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style={divStyle}>{count_variable}</span>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}

胡说叔叔

render = () => {&nbsp; const count = this.get_count(); //this function returns an&nbsp;&nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>counter</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style={color: count === 0 ? 'red' : count === 1 ? 'blue' : 'green'}>{count}</span>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript