jQuery Reactjs 将 html 字符串转换为 jsx

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19266197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:34:01  来源:igfitidea点击:

Reactjs convert html string to jsx

javascriptjqueryajaxreactjs

提问by Peter Wateber

I'm having trouble dealing with facebook's ReactJS. Whenever I do ajax and want to display an html data, ReactJS displays it as text. (See figure below)

我在处理 facebook 的 ReactJS 时遇到了麻烦。每当我执行 ajax 并想要显示 html 数据时,ReactJS 都会将其显示为文本。(见下图)

ReactJS render string

ReactJS 渲染字符串

The data is displayed through the success callback function of the jquery Ajax.

通过jquery Ajax的success回调函数显示数据。

$.ajax({
   url: url here,
   dataType: "json",
   success: function(data) {
      this.setState({
           action: data.action
      })
   }.bind(this)
});

enter image description here

在此处输入图片说明

Is there any easy way to convert this into html? How should I do it using ReactJS?

有没有什么简单的方法可以将其转换为 html?我应该如何使用 ReactJS 做到这一点?

回答by Sophie Alpert

By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTMLproperty:

默认情况下,React 会转义 HTML 以防止XSS(跨站点脚本)。如果你真的想呈现 HTML,你可以使用dangerouslySetInnerHTML属性:

<td dangerouslySetInnerHTML={{__html: this.state.actions}} />

React forces this intentionally-cumbersome syntax so that you don't accidentally render text as HTML and introduce XSS bugs.

React 强制使用这种有意繁琐的语法,这样您就不会意外地将文本呈现为 HTML 并引入 XSS 错误。

回答by Brett DeWoody

There are now safer methods to accomplish this. The docs have been updatedwith these methods.

现在有更安全的方法来实现这一点。该文档已更新,使用这些方法。

Other Methods

其他方法

  1. Easiest- Use Unicode, save the file as UTF-8 and set the charsetto UTF-8.

    <div>{'First · Second'}</div>

  2. Safer- Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort- Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

  1. 最简单- 使用 Unicode,将文件另存为 UTF-8 并将 设置charset为 UTF-8。

    <div>{'First · Second'}</div>

  2. 更安全- 对 Javascript 字符串中的实体使用 Unicode 编号。

    <div>{'First \u00b7 Second'}</div>

    或者

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. 或者带有字符串和 JSX 元素的混合数组。

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. 最后的手段- 使用dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

回答by Arman Nisch

I recommend using Interweavecreated by milesj. Its a phenomenal library that makes use of a number if ingenious techniques to parse and safely insert HTML into the DOM.

我建议使用交织产生的milesj。它是一个非凡的库,它使用了一些巧妙的技术来解析 HTML 并将其安全地插入到 DOM 中。

Interweave is a react library to safely render HTML, filter attributes, autowrap text with matchers, render emoji characters, and much more.

Interweave 是一个反应库,可以安全地呈现 HTML、过滤属性、使用匹配器自动换行文本、呈现表情符号字符等等。

  • Interweave is a robust React library that can:
    • Safely render HTML without using dangerouslySetInnerHTML.
    • Safely strip HTML tags.
    • Automatic XSS and injection protection.
    • Clean HTML attributes using filters.
    • Interpolate components using matchers.
    • Autolink URLs, IPs, emails, and hashtags.
    • Render Emoji and emoticon characters.
    • And much more!
  • Interweave 是一个强大的 React 库,它可以:
    • 在不使用危险的SetInnerHTML 的情况下安全地呈现HTML。
    • 安全地剥离 HTML 标签。
    • 自动 XSS 和注入保护。
    • 使用过滤器清理 HTML 属性。
    • 使用匹配器插入组件。
    • 自动链接 URL、IP、电子邮件和主题标签。
    • 渲染表情符号和表情符号。
    • 以及更多!

Usage Example:

用法示例:

import React from 'react';
import { Markup } from 'interweave';

const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b> </p><p>Facere debitis impedit doloremque eveniet eligendi reiciendis <u>ratione obcaecati repellendus</u> culpa? Blanditiis enim cum tenetur non rem, atque, earum quis, reprehenderit accusantium iure quas beatae.</p><p>Lorem ipsum dolor sit amet <a href='#testLink'>this is a link, click me</a> Sunt ducimus corrupti? Eveniet velit numquam deleniti, delectus  <ol><li>reiciendis ratione obcaecati</li><li>repellendus culpa? Blanditiis enim</li><li>cum tenetur non rem, atque, earum quis,</li></ol>reprehenderit accusantium iure quas beatae.</p>"

<Markup content={articleContent} /> // this will take the articleContent string and convert it to HTML markup. See: https://milesj.gitbook.io/interweave


//to install package using npm, execute the command
npm install interweave

回答by Donatas Kuskys

npm i html-react-parser;

import Parser from 'html-react-parser';

<td>{Parser(this.state.archyves)}</td>

回答by Hassan Gilak

i found this js fiddle. this works like this

我发现了这个 js 小提琴。这就像这样

function unescapeHTML(html) {
    var escapeEl = document.createElement('textarea');
    escapeEl.innerHTML = html;
    return escapeEl.textContent;
}

<textarea className="form-control redactor"
                          rows="5" cols="9"
                          defaultValue={unescapeHTML(this.props.destination.description)}
                          name='description'></textarea>

jsfiddlelink

jsfiddle链接

回答by Abhra Dey

You can also use Parser() from html-react-parser. I have used the same. Linkshared.

您还可以使用 html-react-parser 中的 Parser()。我也用过。链接共享。

回答by Dayan

i start using npm package called react-html-parser

我开始使用名为 react-html-parser 的 npm 包

回答by letele

For those still experimenting, npm install react-html-parser

对于那些仍在试验中的人, npm install react-html-parser

When I installed it it had 123628 weekly downloads.

当我安装它时,它每周有 123628 次下载。

import ReactHtmlParser from 'react-html-parser'

<div>{ReactHtmlParser(htmlString)}</div>