I want to render the pure HTML coming from some external source into react component. I saw few solutions where people are talking about some conversion tools (HTML to JSX) but I want to handle everything in my component so while mounting it will get the HTML response and that needs to render.
我想将来自某些外部源的纯HTML呈现为react组件。我看到很少有人在谈论一些转换工具(HTML到JSX)的解决方案,但我想处理组件中的所有内容,因此在安装它时会得到HTML响应并且需要呈现。
2 个解决方案
#1
1
You can use dangerouslySetInnerHTML for this:
你可以使用dangerouslySetInnerHTML:
function createMarkup() { return {__html: 'First · Second'}; };
<div dangerouslySetInnerHTML={createMarkup()} />
But as the method name suggests: you should be very sure of what you are doing there and the security implications it has.
但正如方法名称所暗示的那样:你应该非常确定你在那里做了什么以及它带来的安全隐患。
#2
0
This shouldn't be difficult to do . Assign your HTML to a div and then render it using {variable name}
JSX allows you to do this and with ES6 integration you can also use class
instead of className
.
这应该不难做到。将您的HTML分配给div,然后使用{variable name}进行渲染.JSX允许您执行此操作,并且通过ES6集成,您还可以使用class而不是className。
var Hello = React.createClass({
render: function() {
var htmlDiv = <div>How are you</div>
return <div>Hello {this.props.name}
{htmlDiv}
</div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
#1
1
You can use dangerouslySetInnerHTML for this:
你可以使用dangerouslySetInnerHTML:
function createMarkup() { return {__html: 'First · Second'}; };
<div dangerouslySetInnerHTML={createMarkup()} />
But as the method name suggests: you should be very sure of what you are doing there and the security implications it has.
但正如方法名称所暗示的那样:你应该非常确定你在那里做了什么以及它带来的安全隐患。
#2
0
This shouldn't be difficult to do . Assign your HTML to a div and then render it using {variable name}
JSX allows you to do this and with ES6 integration you can also use class
instead of className
.
这应该不难做到。将您的HTML分配给div,然后使用{variable name}进行渲染.JSX允许您执行此操作,并且通过ES6集成,您还可以使用class而不是className。
var Hello = React.createClass({
render: function() {
var htmlDiv = <div>How are you</div>
return <div>Hello {this.props.name}
{htmlDiv}
</div>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>