can.props可以用来设置div标签的样式吗?

时间:2017-09-01 10:40:03

标签: reactjs reactjs.net

我想在div标签中使用this.props数据。我有数据中的颜色,我想动态设置。是否可以在div标签中使用this.props?

var cont =  {
      height: "90px",
  width: "20%",
  background: "LightBlue",
  display: "inline-block",
  padding: "5px",
      margin: "5px"
};

var Comment = React.createClass({    
    render: function () {
      return (
          <div style={cont}>
              <span>
                  {this.props.author}
                  {this.props.col}
              </span> 
          </div>   
      );
    }
});

2 个答案:

答案 0 :(得分:1)

查找

var Comment = React.createClass({
    render: function() {
        return (
            <div style={{backgroundColor: this.props.col}}>
                <span>
                    {this.props.author}
                    {this.props.col}
                </span>
            </div>
        );
    }
});

this.props.color这里是Comment组件的支柱,而不是div的支柱。您可以在此组件中的任何位置使用此支柱。

正如@MayankShukla所说,为了更新样式对象中的字段,您可以使用Object.assign

答案 1 :(得分:0)

试试这个:

<div style={{backgroundColor: this.props.col}}>

Offical React style documentation