[英]React: HTML not rendering correctly
I have this React component whose main goal is to render an article stored ad MarkDown (.md file) after it is transformed into HTML by marked
. 我有这个React组件,其主要目标是在将
marked
为的文章转换为HTML之后,呈现文章存储的广告MarkDown(.md文件)。
import React from 'react';
import marked from 'marked';
import './articles.css';
export default class Articles extends React.Component {
constructor(props) {
super(props);
this.state = {
articles: [],
last_article: ""
}
}
componentWillMount() {
fetch('/last_article', {
headers: {
'Accept': 'text/markdown'
}
})
.then(res => res.text())
.then(txt => marked(txt))
.then(html => {
this.setState({
last_article: html
});
});
}
render() {
return (
<div className="articles">
{this.state.last_article}
</div>
);
}
}
The back-end works fine and componentWillMount
fetches the correct text and transforms it perfectly. 后端工作正常,
componentWillMount
提取正确的文本并将其完美转换。 But it renders like this: 但是它呈现为:
I am not a React expert and never faced this problem before. 我不是React专家,以前从未遇到过这个问题。
Any suggestions? 有什么建议么?
Use the dangerouslySetInnerHTML
approach as I have described below. 使用我下面描述的
dangerouslySetInnerHTML
方法。
Go through this link to see the proper documentation about dangerouslySetInnerHTML and it's side effects 浏览此链接以查看有关dragonallySetInnerHTML及其副作用的正确文档。
class Articles extends React.Component { constructor(props) { super(props); this.state = { articles: [], last_article: "" } } componentWillMount() { this.setState({ last_article: `<h1>Hello</h1>` }); } getMarkdownText() { return { __html: this.state.last_article }; } render() { return ( <div className="articles" dangerouslySetInnerHTML={this.getMarkdownText()}/> ); } } ReactDOM.render( <Articles />, document.getElementById('root') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
就像其他人所说的那样,危险地SetInnerHTML可以正常工作,但是如果您发现自己经常这样做, 请查看这个很棒的lib 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.