Javascript 在 React 组件中将 HTML 字符串渲染为真正的 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39758136/
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
Render HTML string as real HTML in a React component
提问by Sergio Tapia
Here's what I tried and how it goes wrong.
这是我尝试过的方法以及它是如何出错的。
This works:
这有效:
<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />
This doesn't:
这不会:
<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />
The description property is just a normal string of HTML content. However it's rendered as a string, not as HTML for some reason.
description 属性只是一个普通的 HTML 内容字符串。但是,由于某种原因,它呈现为字符串,而不是 HTML。
Any suggestions?
有什么建议?
采纳答案by Sergio Flores
Check if the text you're trying to append to the node is not escaped like this:
检查您尝试附加到节点的文本是否没有像这样转义:
var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};
Instead of this:
取而代之的是:
var prop = {
match: {
description: '<h1>Hi there!</h1>'
}
};
if is escaped you should convert it from your server-side.
如果被转义,你应该从你的服务器端转换它。
The node is text because is escaped
该节点是文本,因为已转义
The node is a dom node because isn't escaped
该节点是一个 dom 节点,因为它没有被转义
回答by Ilanus
Does this.props.match.description
Is a string or an object? If it's a string, it should be converted to HTML just fine. Example:
确实this.props.match.description
是一个字符串或一个对象?如果它是一个字符串,它应该被转换为 HTML 就好了。例子:
class App extends React.Component {
constructor() {
super();
this.state = {
description: '<h1 style="color:red;">something</h1>'
}
}
render() {
return (
<div dangerouslySetInnerHTML={{ __html: this.state.description }} />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Result: http://codepen.io/ilanus/pen/QKgoLA?editors=1011
结果:http: //codepen.io/ilanus/pen/QKgoLA?editors=1011
However if description: <h1 style="color:red;">something</h1>
without the quotes ''
you're going to get:
但是,如果description: <h1 style="color:red;">something</h1>
没有引号,''
您将得到:
?Object {
$$typeof: [object Symbol] {},
_owner: null,
key: null,
props: Object {
children: "something",
style: "color:red;"
},
ref: null,
type: "h1"
}
If It's a string and you don't see any HTML markup the only problem i see is wrong markup..
如果它是一个字符串并且您没有看到任何 HTML 标记,那么我看到的唯一问题是错误标记。
UPDATE
更新
If you are dealing with HTMLEntitles. You need to decode them before sending them to dangerouslySetInnerHTML
that's why they called it dangerously :)
如果您正在处理 HTMLEntitles。您需要在将它们发送给它们之前对其进行解码,dangerouslySetInnerHTML
这就是为什么他们将其称为危险的原因:)
Working example:
工作示例:
class App extends React.Component {
constructor() {
super();
this.state = {
description: '<p><strong>Our Opportunity:</strong></p>'
}
}
htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
render() {
return (
<div dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.state.description) }} />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
回答by pixelearth
I used 'react-html-parser'
我使用了'react-html-parser'
yarn add react-html-parser
import ReactHtmlParser from 'react-html-parser';
<div> { ReactHtmlParser (html_string) } </div>
Source on npmjs.com
Lifting up @okram's comment for more visibility:
提升@okram 的评论以获得更多可见性:
from its github description: Converts HTML strings directly into React components avoiding the need to use dangerouslySetInnerHTML from npmjs.com A utility for converting HTML strings into React components. Avoids the use of dangerouslySetInnerHTML and converts standard HTML elements, attributes and inline styles into their React equivalents.
来自其 github 描述:将 HTML 字符串直接转换为 React 组件,避免使用来自 npmjs.com 的危险的SetInnerHTML 一个用于将 HTML 字符串转换为 React 组件的实用程序。避免使用危险的SetInnerHTML 并将标准的 HTML 元素、属性和内联样式转换为它们的 React 等效项。
回答by Brad Adams
If you have control over where the string containing html is coming from (ie. somewhere in your app), you can benefit from the new <Fragment>
API, doing something like:
如果您可以控制包含 html 的字符串来自何处(即在您的应用程序中的某个地方),您可以从新<Fragment>
API 中受益,执行以下操作:
import React, {Fragment} from 'react'
const stringsSomeWithHtml = {
testOne: (
<Fragment>
Some text <strong>wrapped with strong</strong>
</Fragment>
),
testTwo: `This is just a plain string, but it'll print fine too`,
}
...
render() {
return <div>{stringsSomeWithHtml[prop.key]}</div>
}
回答by ???? ????? ?????? ???? ? ?????
dangerouslySetInnerHTML
危险地SetInnerHTML
dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it's easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it's dangerous. For example:
risklySetInnerHTML 是 React 在浏览器 DOM 中使用 innerHTML 的替代品。一般来说,从代码中设置 HTML 是有风险的,因为很容易在不经意间将用户暴露给跨站点脚本 (XSS) 攻击。所以,你可以直接从 React 设置 HTML,但是你必须输入危险的 SetInnerHTML 并传递一个带有 __html 键的对象,以提醒自己这是危险的。例如:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
回答by Hou Soune
You just use dangerouslySetInnerHTML method of React
您只需使用 React 的危险的SetInnerHTML 方法
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
Or you can implement more with this easy way: Render the HTML raw in React app
或者你可以用这个简单的方法实现更多:在 React 应用程序中渲染 HTML 原始数据
回答by Lorenzo Delana
I use innerHTML together a ref to span:
我将 innerHTML 与 ref 一起使用来跨越:
import React, { useRef, useEffect, useState } from 'react';
export default function Sample() {
const spanRef = useRef<HTMLSpanElement>(null);
const [someHTML,] = useState("some <b>bold</b>");
useEffect(() => {
if (spanRef.current) {
spanRef.current.innerHTML = someHTML;
}
}, [spanRef.current, someHTML]);
return <div>
my custom text follows<br />
<span ref={spanRef} />
</div>
}
回答by Salman Lone
In my case, I used react-render-html
就我而言,我使用了react-render-html
First install the package by npm i --save react-render-html
首先安装包 npm i --save react-render-html
then,
然后,
import renderHTML from 'react-render-html';
renderHTML("<a class='github' href='https://github.com'><b>GitHub</b></a>")
回答by Янов Алексей
i use https://www.npmjs.com/package/html-to-react
我使用https://www.npmjs.com/package/html-to-react
const HtmlToReactParser = require('html-to-react').Parser;
let htmlInput = html.template;
let htmlToReactParser = new HtmlToReactParser();
let reactElement = htmlToReactParser.parse(htmlInput);
return(<div>{reactElement}</div>)
回答by Binita Bharati
I could not get npm build
to work with react-html-parser
. However, in my case, I was able to successfully make use of https://reactjs.org/docs/fragments.html. I had a requirement to show few html unicode characters , but they should not be directly embedded in the JSX. Within the JSX, it had to be picked from the Component's state. Component code snippet is given below :
我无法npm build
与react-html-parser
. 但是,就我而言,我能够成功使用https://reactjs.org/docs/fragments.html。我需要显示很少的 html unicode 字符,但它们不应该直接嵌入到 JSX 中。在 JSX 中,它必须从组件的状态中选取。组件代码片段如下:
constructor()
{
this.state = {
rankMap : {"5" : <Fragment>★ ★ ★ ★ ★</Fragment> ,
"4" : <Fragment>★ ★ ★ ★ ☆</Fragment>,
"3" : <Fragment>★ ★ ★ ☆ ☆</Fragment> ,
"2" : <Fragment>★ ★ ☆ ☆ ☆</Fragment>,
"1" : <Fragment>★ ☆ ☆ ☆ ☆</Fragment>}
};
}
render()
{
return (<div class="card-footer">
<small class="text-muted">{ this.state.rankMap["5"] }</small>
</div>);
}