在 React 中动态加载 Markdown 文件



我使用 markdown-to-jsx 在我的 React 组件中渲染 markdown。

我的问题是我想动态加载 markdown 文件,而不是用import指定它。场景是这发生在文章详细信息页面上,即我从路由参数获取articleId,然后根据该 id,我想加载相应的 markdown 文件,例如article-123.md.

这是我到目前为止所拥有的。如何动态加载 md 文件?

import React, { Component } from 'react'
import Markdown from 'markdown-to-jsx';
import articleMd from './article-123.md'
class Article extends Component {
constructor(props) {
super(props)
this.state = { md: '' }
}
componentWillMount() {
fetch(articleMd)
.then((res) => res.text())
.then((md) => {
this.setState({ md })
})
}
render() {
return (
<div className="article">
<Markdown children={this.state.md}/>
</div>
)
}
}
export default Article

这按原样工作正常,但是如果我删除顶部的import articleMd from './article-123.md'而是直接传递文件路径以获取它,则输出看起来像 index.html,而不是预期的 md 文件。

不能使用动态导入吗?

class Article extends React.Component {
constructor(props) {
super(props)
this.state = { md: '' }
}
async componentDidMount() {
const articleId = this.props.params.articleId; // or however you get your articleId
const file = await import(`./article-${articleId}.md`);
const response = await fetch(file.default);
const text = await response.text();
this.setState({
md: text
})
}
render() {
return (
<div className="article">
<Markdown children={this.state.md} />
</div>
)
}
}

我知道这是一个旧线程,但我刚刚用以下代码解决了这个问题 使用 markdown-to-JSX

import React, { Component } from 'react'
import Markdown from 'markdown-to-jsx'
class Markdown_parser extends Component {


constructor(props) {
super(props)

this.state = { md: "" }
}

componentWillMount() {
const { path } = this.props;
import(`${path}`).then((module)=>

fetch(module.default)
.then((res) => res.text())
.then((md) => {
this.setState({ md })
})
)
}

render() {

let { md } = this.state

return (
<div className="post">
<Markdown children={md} />
</div>
)
}
}

export default Markdown_parser

然后我称类 sa 跟随

<Markdown_parser path = "path-to-your-fle" />

相关内容

最新更新