ReactJS dangerouslySetStyle?

Rob*_*vin 5 reactjs

我正在使用ReactJS,dangerouslySetInnerHTML但我希望能够将元素的style属性设置为原始字符串.我已经搜索过并查看了React源代码但我找不到任何内容.

有没有办法做到这一点?

Bri*_*and 9

您必须在dom节点上手动设置属性才能执行此操作.最简单的方法是使用包装器组件:

<CustomAttribute tag="div" dangerouslySetAttributes={{style: 'color:red'}}>
  red text
</CustomAttribute>
Run Code Online (Sandbox Code Playgroud)

和实际的组件

var DSA = 'dangerouslySetAttributes';
var CustomAttribute = React.createClass({
  setAttributes: function(oldAttrs, attrs){
    var el = this.getDOMNode();
    Object.keys(attrs).forEach(function(key){
      if (oldAttrs[key] !== attrs[key]) 
        el.setAttribute(key, attrs[key]);
    });
  },
  componentDidMount: function(){ 
    this.setAttributes({}, this.props[DSA]);
  },
  componentWillReceiveProps: function(nextProps){ 
    this.setAttributes(this.props[DSA], nextProps[DSA]);
  },
  render: function(){
    var Tag = this.props.tag || 'div';
    return <Tag>{this.props.children}</Tag>
  },
});
Run Code Online (Sandbox Code Playgroud)

*未经测试