所以这是唯一的方式来渲染原始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中重写所有这些内容。

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


当前回答

你可以利用html-to-react npm模块。

注意:我是这个模块的作者,几个小时前刚刚发布了它。请随时报告任何bug或可用性问题。

其他回答

这对我来说很管用:

    render()
    {
        var buff = '';
        for(var k=0; k<10; k++)
        {
            buff += "<span> " + k + " </span>";
        }

        return (
            <div className='pagger'>               
                  <div className='pleft'>
                     <div dangerouslySetInnerHTML={{__html: buff }} />
                  </div>
                  <div className='pright'>
                         <div className='records'>10</div>
                         <div className='records'>50</div>
                         <div className='records records_selected'>100</div>
                         <div className='records'>1000</div>
                     </div>
            </div>
        )
    }

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

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

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

我试过这个纯成分:

const RawHTML = ({children, className = ""}) => 
<div className={className}
  dangerouslySetInnerHTML={{ __html: children.replace(/\n/g, '<br />')}} />

特性

接受classNameprop(更容易设置样式) 将\n替换为<br />(您通常希望这样做) 在使用组件时将内容作为子组件,如下所示: < RawHTML > {myHTML} < / RawHTML >

我已经在Github: RawHTML: ReactJS纯组件中放置了该组件来渲染HTML

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

使用内置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}
    </>)
}

我曾在一些快速且不太规范的情况下使用过这个短语:

// react render method:

render() {
    return (
      <div>
        { this.props.textOrHtml.indexOf('</') !== -1
            ? (
                <div dangerouslySetInnerHTML={{__html: this.props.textOrHtml.replace(/(<? *script)/gi, 'illegalscript')}} >
                </div>
              )
            : this.props.textOrHtml
          }

      </div>
      )
  }