所以这是唯一的方式来渲染原始html与reactjs?
// 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中重写所有这些内容。
也许我想错了。请纠正我。
下面是之前发布的一个不那么武断的RawHTML函数版本。它让你:
配置标签
可选地将换行符替换为<br />
传递额外的道具,RawHTML将传递给创建的元素
提供一个空字符串(RawHTML></RawHTML>)
下面是这个组件:
const RawHTML = ({ children, tag = 'div', nl2br = true, ...rest }) =>
React.createElement(tag, {
dangerouslySetInnerHTML: {
__html: nl2br
? children && children.replace(/\n/g, '<br />')
: children,
},
...rest,
});
RawHTML.propTypes = {
children: PropTypes.string,
nl2br: PropTypes.bool,
tag: PropTypes.string,
};
用法:
<RawHTML>{'First · Second'}</RawHTML>
<RawHTML tag="h2">{'First · Second'}</RawHTML>
<RawHTML tag="h2" className="test">{'First · Second'}</RawHTML>
<RawHTML>{'first line\nsecond line'}</RawHTML>
<RawHTML nl2br={false}>{'first line\nsecond line'}</RawHTML>
<RawHTML></RawHTML>
输出:
<div>First · Second</div>
<h2>First · Second</h2>
<h2 class="test">First · Second</h2>
<div>first line<br>second line</div>
<div>first line
second line</div>
<div></div>
它会打破:
<RawHTML><h1>First · Second</h1></RawHTML>
现在有更安全的方法来呈现HTML。我在之前的回答中提到过这个问题。你有4个选项,最后使用dangerlysetinnerhtml。
渲染HTML的方法
Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.
<div>{'First · Second'}</div>
Safer - Use the Unicode number for the entity inside a Javascript string.
<div>{'First \u00b7 Second'}</div>
or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
Last Resort - Insert raw HTML using dangerouslySetInnerHTML.
<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />