【问题标题】:React: HTML not rendering correctly反应:HTML 未正确呈现
【发布时间】:2017-07-31 05:40:24
【问题描述】:

我有这个 React 组件,它的主要目标是在将文章存储的广告 MarkDown(.md 文件)通过marked 转换为 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 获取正确的文本并完美地转换它。但它呈现如下:

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

有什么建议吗?

【问题讨论】:

标签: javascript html reactjs rendering


【解决方案1】:

使用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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 谢谢!我去看看。
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2011-09-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多