gpt4 book ai didi

javascript - react : HTML not rendering correctly

转载 作者:行者123 更新时间:2023-11-28 12:17:41 26 4
gpt4 key购买 nike

我有这个 React 组件,其主要目标是在通过 marked 将存储的广告 MarkDown 文章(.md 文件)转换为 HTML 后呈现该文章。

Articles.js

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>
);
}

}

后端工作正常,componentWillMount 获取正确的文本并完美地转换它。但它的渲染效果是这样的:

enter image description here

我不是 React 专家,以前从未遇到过这个问题。

有什么建议吗?

最佳答案

使用我在下面描述的dangerouslySetInnerHTML方法。

Go through this link to see the proper documentation about dangerouslySetInnerHTML and it's side effects

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>

关于javascript - react : HTML not rendering correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45408208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com