我使用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文件。
<!DOCTYPE html>
开头。 - Benwebpack.config.js
中进行修改,以添加包含要包含在输出中的.md
文件的路径,但如果您使用create-react-app,则无法这样做(除非您弹出它)... 在后一种情况下,您应该将md文件放置在public
文件夹中。 - marcodt89