React:HTML无法正确呈现

时间:2017-07-31 05:40:25

标签: javascript html reactjs rendering

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

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专家,以前从未遇到过这个问题。

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

使用我在下面描述的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>

答案 1 :(得分:1)

正如其他人所说的那样,危险的SetInnerHTML会起作用,但如果你发现自己经常这样做,check out this cool lib