我正在获取数据,其中一个数据IN fetch看起来像这样
<p><strong>This is my first content and it is supposed to represent my index.</strong></p>
这是服务器上的所见即所得输出,当我试图带到我的屏幕时,我完全按原样得到它。
请告诉我如何将这些数据作为html导入我的页面。
来自这里的文档是一个例子
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
就像名字所暗示的那样,如果你没有经过适当的审查,这是危险的。
有关详细信息,请阅读文档here
您可以通过创建对该元素的引用来编译HTML中的数据,并将innerHTML
属性设置为包含其值中的HTML的获取数据。
这段代码为您提供了更多想法:
constructor() {
super();
// create reference
this.titleDiv = React.createRef();
// this can be whatever you get HTML data from
this.state ={
testHTML: "<h1>Test HTML Text</h1>"
}
}
componentDidMount() {
const element = this.titleDiv.current;
element.innerHTML = this.state.testHTML;
}
render() {
return (
// define reference for where you want to set HTML
<div ref={this.titleDiv}></div>
)
}
你可以深入了解react.js中的ref
:https://reactjs.org/docs/refs-and-the-dom.html