【问题标题】:React how to inline style different objects in one element反应如何在一个元素中内联样式不同的对象
【发布时间】:2019-06-30 15:44:08
【问题描述】:

在 React 中,我试图将样式仅应用于像 h1 这样的元素内部的一个对象,这是一个示例

const Header = () => {

  const firstName = "Ashraf";
  const lastName = "Fathi";
  const date = new Date();
  const hours = date.getHours();

  let timeOfDay;
  const styles = {
    color: ""
  }
  if (hours < 12) {
    timeOfDay = "Good morning"
    styles.color = "#ff474d"
  }
  else if (hours >= 12 && hours < 17) {
    timeOfDay = "Good afternoon"
    styles.color = "#7b5dff"
  }
  else {
    timeOfDay = "Good night"
    styles.color = "#01ff41"
  }
  return(
    <div>
          <h1 className="navbar" style={styles}>{timeOfDay} {`${firstName} ${lastName}`} It is currently {hours} clock</h1>
    </div>
    )
}

我想要做的是将样式仅应用于 timeOfDay 那么我该如何实现呢?我尝试了不同的方法,但这一切都归结为 style={} 影响了不寻找的整个元素。提前致谢

【问题讨论】:

    标签: javascript css node.js reactjs ecmascript-6


    【解决方案1】:

    timeOfDay 周围添加一个span,然后将样式传递给它

     <div>
          <h1 className="navbar"><span style={styles}>{timeOfDay}</span> {`${firstName} ${lastName}`} It is currently {hours} clock</h1>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2020-09-05
      • 2016-04-14
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      相关资源
      最近更新 更多