我看到它的方式是你要解决2个问题.第一个是如何在React中设置元素的innerHTML.另一种是如何根据给定变量(例如当前路线,文本字段的输入等)来获取要呈现的特定HTML.
1.设置元素的innerHTML
你可以使用dangerouslySetInnerHTML prop来做到这一点.顾名思义,它将所述元素的innerHTML设置为您指定的任何内容……是的,“危险”是准确的,因为它旨在让您在使用此功能之前三思而后行.
Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.
查看此Demo或下面的代码段.
var Demo = React.createClass({
getInitialState: function() {
return {showExternalHTML: false};
},
render: function() {
return (
Toggle Html
{this.state.showExternalHTML ?
);
},
toggleExternalHTML: function() {
this.setState({showExternalHTML: !this.state.showExternalHTML});
}