this.props.match.description 是字符串还是对象?如果它是一个字符串,它应该被转换为 HTML 就好了。示例:
class App extends React.Component {
constructor() {
super();
this.state = {
description: '<h1 style="color:red;">something</h1>'
}
}
render() {
return (
<div dangerouslySetInnerHTML={{ __html: this.state.description }} />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
结果:http://codepen.io/ilanus/pen/QKgoLA?editors=1011
但是,如果描述是 <h1 style="color:red;">something</h1> 没有引号 '',你会得到:
Object {
$$typeof: [object Symbol] {},
_owner: null,
key: null,
props: Object {
children: "something",
style: "color:red;"
},
ref: null,
type: "h1"
}
如果它是一个字符串并且您没有看到任何 HTML 标记,那么我看到的唯一问题是错误标记..
更新
如果您正在处理 HTML 实体,您需要在将它们发送到 dangerouslySetInnerHTML 之前对其进行解码,这就是为什么它被称为“危险”:)
工作示例:
class App extends React.Component {
constructor() {
super();
this.state = {
description: '<p><strong>Our Opportunity:</strong></p>'
}
}
htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
render() {
return (
<div dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.description) }} />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));