【问题标题】:reactjs how to style with an object instead of using in-line styling?reactjs如何使用对象设置样式而不是使用内联样式?
【发布时间】:2018-09-10 16:51:10
【问题描述】:

这是我的代码:

ReactDOM.render(
    <h1 style = {{color:"red"}}>Foo</h1>,
    document.getElementById("root")
)

这是怎么回事 ^ 但这不是:

var styles = {
    color:"red"
}
ReactDOM.render(
    <h1 style = {{styles}}>Foo</h1>,
    document.getElementById("root")
)

我想轻松地设置样式,而不必在每次创建新的 DOM 元素时都输入每种样式...

【问题讨论】:

  • 如果答案有效,您介意选择它作为答案吗?

标签: javascript css reactjs jsx babeljs


【解决方案1】:

在渲染中使用单括号。像这样:

ReactDOM.render(
    <h1 style = {styles}>Foo</h1>,
    document.getElementById("root")
)

style={{ styles }} 不起作用的原因是因为它与style={{ styles: styles }} 相同,它传递具有styles 属性的对象,而不是您为其定义的实际样式。

【讨论】:

  • 好吧,我不知道它只是返回了对象。非常感谢!
猜你喜欢
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 2012-08-01
  • 2017-10-21
相关资源
最近更新 更多