使用reactjs渲染原始HTML

那么这是用reactjs渲染原始html的唯一方法吗?


// http://facebook.github.io/react/docs/tutorial.html

// tutorial7.js

var converter = new Showdown.converter();

var Comment = React.createClass({

  render: function() {

    var rawMarkup = converter.makeHtml(this.props.children.toString());

    return (

      <div className="comment">

        <h2 className="commentAuthor">

          {this.props.author}

        </h2>

        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />

      </div>

    );

  }

});

我知道有一些很酷的方法来用JSX标记内容,但是我主要感兴趣的是能够呈现原始html(包括所有类,内联样式等)。像这样复杂的事情:


<!-- http://getbootstrap.com/components/#dropdowns-example -->

<div class="dropdown">

  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">

    Dropdown

    <span class="caret"></span>

  </button>

  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">

    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>

    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>

    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>

    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>

  </ul>

</div>

我不想在JSX中重写所有内容。


也许我在想这一切错。请纠正我。


阿波罗的战车
浏览 992回答 3
3回答

沧海一幻觉

您可以利用html-to-reactnpm模块。注意:我是该模块的作者,几小时前刚刚发布了该模块。请随时报告任何错误或可用性问题。

湖上湖

我在快速而肮脏的情况下使用了此方法:// react render method:render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; { this.props.textOrHtml.indexOf('</') !== -1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div dangerouslySetInnerHTML={{__html: this.props.textOrHtml.replace(/(<? *script)/gi, 'illegalscript')}} >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : this.props.textOrHtml&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; )&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP