在 React 组件中将 HTML 字符串渲染为真正的 HTML [英] Render HTML string as real HTML in a React component

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

问题描述

这是我尝试过的方法以及它是如何出错的.

这有效:

你好!</h1>"}}/>

这不会:

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

<小时>

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

有什么建议吗?

解决方案

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

var prop = {比赛: {description: '<h1&gt;你好!&lt;/h1>'}};

取而代之的是:

var prop = {比赛: {描述:'

你好!

'}};

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

节点是文本,因为被转义

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

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

This works:

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

This doesn't:

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


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

Any suggestions?

解决方案

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;'
    }
};

Instead of this:

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

The node is a dom node because isn't escaped

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

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