以下是我尝试过的方法,以及出错的地方。
如此:
<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />
这不是:
<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />
description属性只是一个普通的HTML内容字符串。然而,由于某些原因,它被呈现为字符串,而不是HTML。
有什么建议吗?
以下是我尝试过的方法,以及出错的地方。
如此:
<div dangerouslySetInnerHTML={{ __html: "<h1>Hi there!</h1>" }} />
这不是:
<div dangerouslySetInnerHTML={{ __html: this.props.match.description }} />
description属性只是一个普通的HTML内容字符串。然而,由于某些原因,它被呈现为字符串,而不是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>
其他回答
你也可以使用跳线包中的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
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'));
结果:http://codepen.io/ilanus/pen/QKgoLA?editors=1011
但是如果description是<h1 style="color:red;">something</h1> without the quotes ",你会得到:
Object {
$$typeof: [object Symbol] {},
_owner: null,
key: null,
props: Object {
children: "something",
style: "color:red;"
},
ref: null,
type: "h1"
}
如果它是一个字符串,你没有看到任何HTML标记,我看到的唯一问题是错误的标记..
更新
如果你正在处理HTML实体,你需要解码他们之前发送他们到dangerlysetinnerhtml,这就是为什么它被称为“dangerous”:)
工作的例子:
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'));
我不能让npm构建与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>);
}
我使用innerHTML一起引用span:
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>
}
更新:
我删除了一些html状态,并添加了注释,以使示例更符合概念。
/**
* example how to retrieve a reference to an html object
*/
import React, { useRef, useEffect } from 'react';
/**
* this component can be used into another for example <Sample/>
*/
export default function Sample() {
/**
* 1) spanRef is now a React.RefObject<HTMLSpanElement>
* initially created with null value
*/
const spanRef = useRef<HTMLSpanElement>(null);
/**
* 2) later, when spanRef changes because html span element with ref attribute,
* follow useEffect hook will triggered because of dependent [spanRef].
* in an if ( spanRef.current ) that states if spanRef assigned to valid html obj
* we do what we need : in this case through current.innerHTML
*/
useEffect(() => {
if (spanRef.current) {
spanRef.current.innerHTML = "some <b>bold</b>";
}
}, [spanRef]);
return <div>
my custom text follows<br />
{/* ref={spanRef] will update the React.RefObject `spanRef` when html obj ready */}
<span ref={spanRef} />
</div>
}
在我的例子中,我使用了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>")