【问题标题】:can this.props be used to style the div tag?this.props 可以用来设置 div 标签的样式吗?
【发布时间】:2017-09-01 10:40:03
【问题描述】:

我想在 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>   
      );
    }
});

【问题讨论】:

  • &lt;div style={{color: this.props.color}}&gt;&lt;/div&gt;
  • 我添加了一个样式
    ,如何将 style={{backgroundColor: this.props.col}} 再次添加到同一个 div?
  • 像这样:style={Object.assign({}, cont, {backgroundColor: 'red', border:'10px'})} 或使用style={{...cont, backgroundColor: 'red'}}
  • @MayankShukla 谢谢,以上解决方案有效

标签: reactjs reactjs.net


【解决方案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

【讨论】:

  • var cont = { height: "90px", width: "20%", background: "LightBlue", display: "inline-block", padding: "5px", margin: "5px" }; var Comment = React.createClass({ render: function () { return (
    {this.props.author} {this.props.col}
    ); } });我已经添加了一个样式,如何使用 this.prop 添加背景颜色?
【解决方案2】:

试试这个:

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

Offical React style documentation

【讨论】:

  • 我添加了一个样式
    ,如何将 style={{backgroundColor: this.props.col}} 再次添加到同一个 div?
猜你喜欢
相关资源
最近更新 更多
热门标签