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

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

问题描述

这是我尝试过的以及它出错的方式。



这个工作原理:

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

这不是:

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






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





有什么建议?

解决方案

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

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

取而代之:

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

如果被转义,您应该从服务器端转换它。





节点是文字因为被转义了





该节点是一个dom节点,因为isn'没有逃脱

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 no 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天全站免登陆