react 中渲染html_如何在React中渲染HTML

在React应用中从WYSIWYG编辑器插入HTML字符串时,可以使用`dangerouslySetInnerHTML`属性或第三方库如'react-html-parser'来实现。但需要注意`dangerouslySetInnerHTML`可能导致XSS问题,而第三方库可能不再维护。最终,选择合适的方法取决于对安全性和灵活性的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

react 中渲染html

I had this problem - I needed to add an HTML string in a React application, coming from a WYSIWYG editor, but simply adding {myString} to the JSX was escaping the HTML.. so the HTML tags were displayed to the user!

我遇到了这个问题-我需要在WYSIWYG编辑器中的React应用程序中添加HTML字符串,但是将{myString}添加到JSX就是将HTML转义。.因此,向用户显示了HTML标签!

How did I solve it? I saw 2 solutions, basically. The first native, the second required a library.

我该如何解决? 我基本上看到了2个解决方案。 第一个本机,第二个本机需要一个库。

第一个解决方案: dangerouslySetInnerHTML使用dangerouslySetInnerHTML (First solution: use dangerouslySetInnerHTML)

You can use the dangerouslySetInnerHTML attribute on an HTML element to add an HTML string inside its content:

您可以在HTML元素上使用dangerouslySetInnerHTML属性在其内容内添加HTML字符串:

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

Remember that it’s called dangerously for a reason. HTML is not escaped at all in this case, and it might cause XSS issues.

请记住,它被称为危险是有原因的。 在这种情况下,HTML根本不会转义,这可能会导致XSS问题。

But there are good use cases for this.

但是有很好的用例。

第二种解决方案:使用第三方库 (Second solution: use a 3rd party library)

There are many libraries that implement the functionality that dangerouslySetInnerHTML provides, in a simpler way.

有许多库以更简单的方式实现了dangerouslySetInnerHTML提供的功能。

One of them is the react-html-parser library.

其中之一是react-html-parser库。

See the library on GitHub: https://github.com/wrakky/react-html-parser

参见GitHub上的库: https : //github.com/wrakky/react-html-parser

Warning: at the time of writing, it’s not been updated in the last 2 years, so things might break in the future. It worked for me.

警告:在撰写本文时,它在过去两年中尚未更新,因此将来可能会中断。 它为我工作。

使用哪一个? (Which one to use?)

You can look for other similar libraries, but in the end I chose to use the dangerouslySetInnerHTML way.

您可以寻找其他类似的库,但最后我选择使用dangerouslySetInnerHTML方式。

This dangerously-looking name was a built-in reminder to pay attention at correctly whitelisting the HTML tags I allowed the user to enter to that HTML string.

这个看起来很危险的名称是一个内置的提醒,请注意正确将我允许用户输入该HTML字符串HTML标签列入白名单。

翻译自: https://flaviocopes.com/how-to-render-html-react/

react 中渲染html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值