[英]React.js dangerouslySetInnerHTML causing [object Error] {}
I'm using React.我正在使用 React。 I have a string variable in state containing HTML text.
我在 state 中有一个字符串变量,其中包含 HTML 文本。 This text changes, so I need to be able to insert it into my page and have it appear as rendered HTML, not just a string of text.
此文本发生变化,因此我需要能够将其插入到我的页面中并使其呈现为 HTML,而不仅仅是一串文本。 While I've found some third-party work-arounds, it seems the most direct option is to use the
dangerouslySetInnerHTML
property.虽然我找到了一些第三方解决方法,但最直接的选择似乎是使用
dangerouslySetInnerHTML
属性。 but when I do this, the whole page disappears and my console shows但是当我这样做时,整个页面都消失了,我的控制台显示
// [object Error]
{}
Here is an example of what I'm trying to do that produces the same results.这是我尝试做的产生相同结果的示例。
const root = ReactDOM.createRoot(document.getElementById("wrapper"));
class Tester extends React.Component {
constructor(props) {
super(props);
this.state = { num: 1, html: "<b>Odd</b>" };
}
handleClick() {
let num = this.state.num + 1;
let html = "<b>Odd</b>";
if (num % 2 == 0) {
html = "<i>Even</i>";
}
this.setState({ num: num, html: html });
}
render() {
return (
<div>
<h1>Hello {this.state.num}</h1>{" "}
<button onClick={this.handleClick.bind(this)}>Click</button>
{/*<div>{this.state.html}</div>*/}
<div dangerouslySetInnerHTML={{ __HTML: this.state.html }}></div>
</div>
);
}
}
root.render(<Tester />);
I'll note that I am working in CodePen, but that doesn't seem to be the issue.我会注意到我在 CodePen 工作,但这似乎不是问题所在。 I've found others using this method that work just fine.
我发现其他人使用这种方法效果很好。 The link to that CodePen is https://codepen.io/chefdaddyjay/pen/RwyxgeE If you move the comments down a line in the code above, it works, but displays the HTML tags plainly.
该 CodePen 的链接是https://codepen.io/chefdaddyjay/pen/RwyxgeE如果您将上面代码中的注释向下移动一行,它会起作用,但会清楚地显示 HTML 标签。
the "html" inside the brackets should be lowercase like this括号内的“html”应该像这样小写
<div dangerouslySetInnerHTML={{ __html: this.state.html }}></div>
as per the documentation https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml (emphasis mine)根据文档https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml (强调我的)
you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous.
您必须输入 dangerouslySetInnerHTML 并传递带有__html键的 object,以提醒自己这是危险的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.