在 React 组件中将 HTML 字符串呈现为真实的 HTML [英] Render HTML string as real HTML in a React component

查看:29
本文介绍了在 React 组件中将 HTML 字符串呈现为真实的 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于在 React 组件中将 HTML 字符串呈现为真实的 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆