在 React 组件中将 HTML 字符串呈现为真实的 HTML

2022-01-31 00:00:00 reactjs javascript html jsx

这是我尝试过的方法以及出现问题的原因.

Here's what I tried and how it goes wrong.

这行得通:

<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />

这不是:

<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />

<小时>

description 属性只是一个普通的 HTML 内容字符串.但是由于某种原因,它被呈现为字符串,而不是 HTML.


The description property is just a normal string of HTML content. However it's rendered as a string, not as HTML for some reason.

有什么建议吗?

推荐答案

检查您尝试附加到节点的文本是否没有像这样转义:

Check if the text you're trying to append to the node is not escaped like this:

var prop = {
    match: {
        description: '&lt;h1&gt;Hi there!&lt;/h1&gt;'
    }
};

而不是这个:

var prop = {
    match: {
        description: '<h1>Hi there!</h1>'
    }
};

如果被转义,你应该从你的服务器端转换它.

if is escaped you should convert it from your server-side.

节点是文本,因为被转义了

The node is text because is escaped

该节点是一个dom节点,因为没有转义

The node is a dom node because isn't escaped

相关文章