reactjs - 如何设置backgroundcolor的内联样式?

Duk*_*gal 43 javascript reactjs

我想设置一些元素的样式属性,但我没有正确的语法.任何人都可以建议我错在哪里?

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>
           );
  }

}
Run Code Online (Sandbox Code Playgroud)

更新:对于任何看这个的人,请参阅评论这不是正常工作的代码.

小智 54

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

你不需要报价.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>
Run Code Online (Sandbox Code Playgroud)

  • 当我在反应视图组件中使用它时,我得到`未捕获的ReferenceError:bgColors未定义`错误.我错过了什么吗? (3认同)
  • 该链接重定向到 https://facebook.github.io/react/docs/dom-elements.html。另外,我不喜欢这个关于 React 样式标签的文档,因为它只是告诉你`style 属性接受一个带有camelCased 属性的JavaScript 对象而不是一个CSS 字符串`。它接受所有 CSS 样式吗?包括过渡?正确的 React 样式属性列表会很好。 (2认同)

Cra*_*igo 12

你的报价是错误的.这是一个简单的例子:

<div style={{backgroundColor: "#FF0000"}}>red</div>
Run Code Online (Sandbox Code Playgroud)


lli*_*oor 9

如果你想要多种风格,这是正确的完整答案.这是与类和风格的div:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>
Run Code Online (Sandbox Code Playgroud)