【问题标题】:reactjs - how to set inline style of backgroundcolor?reactjs - 如何设置背景颜色的内联样式?
【发布时间】:2017-06-06 16:29:23
【问题描述】:

我想设置一些元素的样式属性,但语法不正确。谁能建议我错在哪里?

import React from 'react';
import debug from 'debug'

const log = debug('app:component:Header');

var bgColors = { "Default": "#81b71a",
                    "Blue": "#00B1E1",
                    "Cyan": "#37BC9B",
                    "Green": "#8CC152",
                    "Red": "#E9573F",
                    "Yellow": "#F6BB42",
};

export default class SideBar extends React.Component {

  constructor(props) {
    super(props);

  }


  render() {

    return (


    <a style="{{backgroundColor: {bgColors.Default}}}" >default</a>
    <a style="{{backgroundColor: {bgColors.Blue}}}" >blue</a>
    <a style="{{backgroundColor: {bgColors.Cyan}}}" >cyan</a>
    <a style="{{backgroundColor: {bgColors.Green}}}" >green</a>
    <a style="{{backgroundColor: {bgColors.Red}}}"  >red</a>
    <a style="{{backgroundColor: {bgColors.Yellow}}}" >yellow</a>
           );
  }

}

更新:对于任何查看此内容的人,请参阅 cmets 这不是工作代码。

【问题讨论】:

  • 这也行吗?我会认为你必须将这些锚点包装在一个元素中,因为返回应该是一个元素,而不是很多——除非你编辑了一些东西
  • 它可能不起作用。我从一段更大的代码中破解了它。
  • 这是正确的语法:&lt;p style= {{color:'gray'}}&gt;{props.item.text}&lt;/p&gt;

标签: javascript reactjs


【解决方案1】:

https://facebook.github.io/react/tips/inline-styles.html

你不需要引号。

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

【讨论】:

  • 我在反应视图组件中使用 Uncaught ReferenceError: bgColors is not defined 错误。我错过了什么吗?
  • 该链接重定向到facebook.github.io/react/docs/dom-elements.html。另外,我不喜欢这个关于 React 样式标签的文档,因为它只是告诉你 The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string。它接受所有 CSS 样式吗?包括过渡?正确的 React 样式属性列表会很好。
【解决方案2】:

您的引语放错了位置。这是一个简单的例子:

<div style={{backgroundColor: "#FF0000"}}>red</div>

【讨论】:

    【解决方案3】:

    如果您想要不止一种风格,这是正确的完整答案。 这是具有类和样式的 div:

    <div className="class-example" style={{width: '300px', height: '150px'}}></div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2019-06-21
      • 1970-01-01
      • 2023-03-09
      • 2015-03-04
      • 2019-09-28
      • 2019-10-19
      相关资源
      最近更新 更多