以下是我尝试过的方法,以及出错的地方。

如此:

<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />

这不是:

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

description属性只是一个普通的HTML内容字符串。然而,由于某些原因,它被呈现为字符串,而不是HTML。

有什么建议吗?


当前回答

你也可以使用跳线包中的parseReactHTMLComponent。看一下就知道,它很简单,不需要使用JSX语法。

https://codesandbox.io/s/jumper-module-react-simple-parser-3b8c9?file=/src/App.js。

关于跳线的更多信息:

https://github.com/Grano22/jumper/blob/master/components.js

NPM包:

https://www.npmjs.com/package/jumper_react

其他回答

在我的例子中,我使用了react-render-html

首先通过npm i安装这个包——save react-render-html

然后,

import renderHTML from 'react-render-html';

renderHTML("<a class='github' href='https://github.com'><b>GitHub</b></a>")

// For typescript import parse, { HTMLReactParserOptions } from "html-react-parser"; import { Element } from "domhandler/lib/node"; export function contentHandler(postContent: string) { const options: HTMLReactParserOptions = { replace: (domNode: Element) => { if (domNode.attribs) { if (domNode.attribs.id === 'shortcode') { return <div className="leadform">Shortcode</div>; } } }, }; return parse(postContent, options); } // Usage: contentHandler("<span>Hello World!</span>")

如果您可以控制{this.props.match.description},并且您正在使用JSX。我建议不要使用“dangerlysetinnerhtml”。

// In JSX, you can define a html object rather than a string to contain raw HTML
let description = <h1>Hi there!</h1>;

// Here is how you print
return (
    {description}
);

你只是使用了React的dangerlysetinnerhtml方法

<div dangerouslySetInnerHTML={{\ __html: htmlsthtml} />

或者你可以用这个简单的方法实现更多:在React应用程序中渲染HTML原始

如果你在字符串中有HTML,我建议使用一个叫做HTML -react-parser的包。

安装

NPM:

npm install html-react-parser

纱:

yarn add html-react-parser

使用

import parse from 'html-react-parser'
const yourHtmlString = '<h1>Hello</h1>'

代码:

<div>
    {parse(yourHtmlString)}
</div>