React App渲染HTML实体(例如&符)转义 [英] React app rendering html entities such as ampersand as escaped

查看:139
本文介绍了React App渲染HTML实体(例如&符)转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Wordpress页面中嵌入了一个React应用程序.它从JSON API中提取内容,并将其显示在各个区域中.

I have a React app embedded in Wordpress page. It pulls content from a JSON api and displays it in various areas.

我的问题是,来自api的所有文本内容都显示为转义字符,即&显示应与号的位置.

My problem is that all of the text content that comes from the api displays as escaped charachters i.e & displays where an ampersand should be.

我的wordpress页面具有<meta charSet="utf-8" />,我通常希望将其转换,但是对React内容没有影响.是因为渲染是在React中完成的吗?在哪种情况下,我需要以某种方式将React设置为使用UTF-8?

My wordpress page has <meta charSet="utf-8" /> which I would normally expect to convert this, but is having no effecton the React content. Is it because the rendering is done within React? In which case do I need to set React somehow to be using UTF-8?

推荐答案

HTML(包括实体)在以表达式形式呈现时将以字符串形式呈现:

HTML (including entities) will be rendered as a string when being rendered as an expression:

{htmlString}

为了解析HTML,有 dangerouslySetInnerHTML 道具:

In order to parse HTML, there is dangerouslySetInnerHTML prop:

<span dangerouslySetInnerHTML={{__html: htmlString }} />

顾名思义,它是不安全的,通常应避免使用.如果字符串来自不受信任的来源或可以被利用的来源,则可以将恶意代码呈现给客户端.

As the name says, it's unsafe and should be generally avoided. If a string comes from untrusted source or a source that could be exploited, malicious code can be rendered to a client.

首选方式是具体解码实体,例如与 html-entities :

The preferable way is to decode entities specifically, e.g. with html-entities:

import { Html5Entities } from 'html-entities';
const htmlEntities = new Html5Entities();

...

{htmlEntities.decode(htmlString)}

可以通过不首先存储HTML实体来避免此问题.

The problem could be avoided by not storing HTML entities in the first place if possible.

这篇关于React App渲染HTML实体(例如&符)转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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