Is 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'));
Result: http://codepen.io/ilanus/pen/QKgoLA?editors=1011 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 标记,那么我看到的唯一问题是错误的标记。
UPDATE
如果您正在处理 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'));