所以这是唯一的方式来渲染原始html与reactjs?

// http://facebook.github.io/react/docs/tutorial.html
// tutorial7.js
var converter = new Showdown.converter();
var Comment = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
      </div>
    );
  }
});

我知道有一些很酷的方法可以用JSX标记东西,但我主要感兴趣的是能够呈现原始html(包括所有的类、内联样式等)。像这样复杂的事情:

<!-- http://getbootstrap.com/components/#dropdowns-example -->
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
  </ul>
</div>

我不想在JSX中重写所有这些内容。

也许我想错了。请纠正我。


当前回答

我使用了这个名为Parser的库。它满足了我的需要。

import React, { Component } from 'react';    
import Parser from 'html-react-parser';

class MyComponent extends Component {
  render() {
    <div>{Parser(this.state.message)}</div>
  }
};

其他回答

除非绝对必要,否则不应该使用dangerlysetinnerhtml。根据文档,“这主要是为了与DOM字符串操作库合作”。当你使用它时,你就放弃了React的DOM管理的好处。

在您的情况下,转换为有效的JSX语法非常简单;只需将类属性更改为className即可。或者,正如上面评论中提到的,你可以使用ReactBootstrap库,它将Bootstrap元素封装到React组件中。

现在有更安全的方法来呈现HTML。我在之前的回答中提到过这个问题。你有4个选项,最后使用dangerlysetinnerhtml。

渲染HTML的方法

Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8. <div>{'First · Second'}</div> 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> Or a mixed array with strings and JSX elements. <div>{['First ', <span>&middot;</span>, ' Second']}</div> Last Resort - Insert raw HTML using dangerouslySetInnerHTML. <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

我需要在我的头脑中使用一个带有onLoad属性的链接,其中div是不允许的,所以这给我带来了巨大的痛苦。我目前的解决方法是关闭原来的脚本标记,做我需要做的,然后打开脚本标记(被原来关闭)。希望这可以帮助那些没有其他选择的人:

<script dangerouslySetInnerHTML={{ __html: `</script>
   <link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>

这里有一个解决方案,可以归结为两个步骤:

使用内置api将原始HTML字符串解析为HTML元素 递归地将Element对象(及其子对象)转换为ReactElement对象。

注:这是一个学习的好例子。但是考虑一下其他答案中描述的选项,比如html-to-react库。

本方案特点:

它不使用dangerlysetinnerhtml 它使用React.createElement 可运行的示例存储库。


下面是.jsx代码:

// RawHtmlToReactExample.jsx
import React from "react";

/**
 * Turn a raw string representing HTML code into an HTML 'Element' object.
 *
 * This uses the technique described by this StackOverflow answer: https://stackoverflow.com/a/35385518
 * Note: this only supports HTML that describes a single top-level element. See the linked post for more options.
 *
 * @param {String} rawHtml A raw string representing HTML code
 * @return {Element} an HTML element
 */
function htmlStringToElement(rawHtml) {
    const template = document.createElement('template');
    rawHtml = rawHtml.trim();
    template.innerHTML = rawHtml;
    return template.content.firstChild;
}

/**
 * Turn an HTML element into a React element.
 *
 * This uses a recursive algorithm. For illustrative purposes it logs to the console.
 *
 * @param {Element} el
 * @return {ReactElement} (or a string in the case of text nodes?)
 */
function elementToReact(el) {
    const tagName = el.tagName?.toLowerCase(); // Note: 'React.createElement' prefers lowercase tag names for HTML elements.
    const descriptor = tagName ?? el.nodeName;
    const childNodes = Array.from(el.childNodes);
    if (childNodes.length > 0) {
        console.log(`This element ('${descriptor}') has child nodes. Let's transform them now.`);
        const childReactElements = childNodes.map(childNode => elementToReact(childNode)).filter(el => {
            // In the edge case that we found an unsupported node type, we'll just filter it out.
            return el !== null
        });
        return React.createElement(tagName, null, ...childReactElements);
    } else {
        // This is a "bottom out" point. The recursion stops here. The element is either a text node, a comment node,
        // and maybe some other types. I'm not totally sure. Reference the docs to understand the different node
        // types: https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
        console.log(`This element ('${descriptor}') has no child nodes.`);

        // For simplicity, let's only support text nodes.
        const nodeType = el.nodeType;
        if (nodeType === Node.TEXT_NODE) {
            return el.textContent;
        } else {
            console.warn(`Unsupported node type: ${nodeType}. Consider improving this function to support this type`);
            return null;
        }
    }
}

export function RawHtmlToReactExample() {
    const myRawHtml = `<p>This is <em>raw</em> HTML with some nested tags. Let's incorporate it into a React element.`;
    const myElement = htmlStringToElement(myRawHtml);
    const myReactElement = elementToReact(myElement);

    return (<>
        <h1>Incorporate Raw HTML into React</h1>

        {/* Technique #1: Use React's 'dangerouslySetInnerHTML' attribute */}
        <div dangerouslySetInnerHTML={{__html: myRawHtml}}></div>

        {/* Technique #2: Use a recursive algorithm to turn an HTML element into a React element */}
        {myReactElement}
    </>)
}

使用类似DOMPurify的东西来净化原始html,然后使用dangerlysetinnerhtml会更安全

我喜欢净化

的类型

NPM I—save-dev @types/dompurify

import React from React import * as DOMPurify from DOMPurify; Let dirty = '<b>hello there</b>'; 净化。消毒(脏的); 函数MyComponent() { return <div dangerlysetinnerhtml ={{__html: clean)}} />; }

如果在您的特定设置中有问题,可以考虑考虑惊人的isomorphic-dompurify项目,它可以解决人们可能遇到的许多问题。

NPM I同构-dompurify

import React from React 从isomorphic-dompurify导入DOMPurify; Const dirty = '<p>hello</p>' const clean = dompurification .sanitize(脏的); 函数MyComponent() { return <div dangerlysetinnerhtml ={{__html: clean)}} />; }

为演示 https://cure53.de/purify

更多的 https://github.com/cure53/DOMPurify

https://github.com/kkomelin/isomorphic-dompurify