首页 > 解决方案 > 将背景颜色动态设置为 div 标签

问题描述

我是新来的反应并试图在反应应用程序中设置 div 标签的背景颜色。下面的代码在为下面的 div 标签渲染时基本上给出了不同的背景颜色。我无法使用以下语法设置值。

         let month= ["January","February","March","April","May","June","July","August","September","October","November","December"];
         let temp;
         let c = '#d8ef8a !important';

         temp = month.indexOf(this.props.label);
       //  console.log(temp);
         if(temp <= 2)
          c = c;
          else if (temp > 2 && temp <= 5)
          c = '#d8ef8a !important';
          else if (temp > 5 && temp <= 8)
          c = '#ffa77b !important';
          else if(temp > 8)
          c = '#d9bdf6 !important';
          else
          c = '#000 !important';
        // console.log(color);
        return (
            <div  style={{ display: 'flex',justifyContent:'center',alignItems:'center', backgroundColor:c, borderLeft:'solid 1px white',position:'absolute',height:20,left:this.props.left,width:this.props.width}}>
                <div>
                {this.props.label}
                </div>
            </div>)

标签: reactjs

解决方案


这段代码中有两件事。首先,如果它小于 2,则不需要颜色c变量,其次,您不需要重要的变量!颜色,因为它一次只需要一种颜色。

temp = month.indexOf("September");
  //Removed extra condition and important statement
  if (temp > 2 && temp <= 5) c = "#d8ef8a ";
  else if (temp > 5 && temp <= 8) c = "#ffa77b ";
  else if (temp > 8) c = "#d9bdf6 ";
  else c = "#000 ";

这是工作代码:https ://codesandbox.io/s/jolly-babbage-mcdlf


推荐阅读