如何将Markdown文件加载到React组件中? [英] How do I load a markdown file into a react component?

查看:578
本文介绍了如何将Markdown文件加载到React组件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将.md markdown文件加载到react组件中?我已经通过Google搜索尝试了那么多npm库,但找不到合适的解决方案.

How would I load a .md markdown file into a react component? I have tried so many npm libraries through google searches and I cant find a good solution.

我想加载.md文件,例如:

I want to load the .md file something like:

render() {
    <div>
        <MarkDown src="about.md" />
    </div>
}

推荐答案

我使用标记( GitHub ).

我首先这样导入它:

import marked from "marked";

然后我在React的componentDidMount事件中获取我的* .md文件,并使用marked(text)(其中text是响应)将其存储在组件的状态下:

I then fetch my *.md file within React's componentDidMount event and store it in my component's state using marked(text) (where text is the response):

componentDidMount() {
  const readmePath = require("./Readme.md");

  fetch(readmePath)
    .then(response => {
      return response.text()
    })
    .then(text => {
      this.setState({
        markdown: marked(text)
      })
    })
}

...最后,我使用dangerouslySetInnerHTML属性将其呈现在页面上:

...and finally I render it on the page using the dangerouslySetInnerHTML attribute:

render() {
  const { markdown } = this.state;

  return (
    <section>
      <article dangerouslySetInnerHTML={{__html: markdown}}></article>
    </section>
  )
}

这篇关于如何将Markdown文件加载到React组件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆