【问题标题】:Can't Conditionally the style set of the span in react (css modules)不能有条件地在反应中设置跨度的样式(css模块)
【发布时间】:2020-11-02 03:46:51
【问题描述】:

我做了什么。

  <span className="status">
    {isOnline}?{styles.online}: {styles.offline}
  </span>

从 JSON 中获取数据。需要根据值设置具体的样式

我在 CSS 模块中有什么:

 .online {
  border: 2px solid green;
}

.offline {
  border: 2px solid red;
}

错误:我没有得到类的值,而是得到了类名

【问题讨论】:

    标签: javascript css reactjs css-modules


    【解决方案1】:
    <span className={`${styles.status} ${isOnline ? styles.online : styles.offline}`}>
    ...
    </span>
    

    【讨论】:

    • 其实我需要改变图片的边框颜色=>图片是{props.avatar},样式是{styles.avatar}
    • 您能帮忙吗,先生?
    • 我需要更多代码才能为您提供帮助,但如果您使用相关代码更新您的问题,我很乐意这样做
    【解决方案2】:
    <span className = {this.state.isOnline ? "status online" : "status offline"} ></span>
    

    class Example extends React.Component {
      state = {
        isOnline: false
      }
    
      handleClick = () => {
        this.setState(state => ({
            isOnline: !state.isOnline
        }))
      }
      
      render() {
        return ( 
          <div >
            < button onClick = {this.handleClick} > 
              Toggle Online 
            </button>  
            <br/>
            <span className = {this.state.isOnline ? "status online" : "status offline"} ></span> 
          </div>
        )
      }
    }
    
    
    
    ReactDOM.render( < Example / > , document.getElementById("root"));
    .online {
      border: 2px solid green;
    }
    
    .offline {
      border: 2px solid red;
    }
    
    .status {
      display: inline-block;
      width: 100px;
      height: 100px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

      【解决方案3】:

      我建议使用classnames 库。它对条件类分配有很大帮助:

      <span className={classnames(styles.status, {
        [styles.online]: isOnline,
        [styles.offline]: !isOnline,
      })}>
      </span>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        • 2021-06-21
        • 2019-08-05
        • 2013-07-29
        • 2012-11-28
        • 2019-12-12
        相关资源
        最近更新 更多