如何将降价文件加载到反应组件中?

新手上路,请多包涵

我如何将 .md 降价文件加载到反应组件中?我通过谷歌搜索尝试了很多 npm 库,但我找不到一个好的解决方案。

代码图像

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

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

原文由 PizzaHead 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 414
2 个回答

我使用 标记GitHub )。

我首先像这样导入它:

 import marked from "marked";

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

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

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

…最后我使用 dangerouslySetInnerHTML 属性在页面上呈现它:

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

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

原文由 James Donnelly 发布,翻译遵循 CC BY-SA 4.0 许可协议

一个完整的工作示例 react-markdown

 import React, { Component } from 'react'
import ReactMarkdown from 'react-markdown'
import termsFrPath from './Terms.fr.md'

class Terms extends Component {
  constructor(props) {
    super(props)

    this.state = { terms: null }
  }

  componentWillMount() {
    fetch(termsFrPath).then((response) => response.text()).then((text) => {
      this.setState({ terms: text })
    })
  }

  render() {
    return (
      <div className="content">
        <ReactMarkdown source={this.state.terms} />
      </div>
    )
  }
}

export default Terms

原文由 Dorian 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进