我使用markdown-to-jsx在我的 React 组件中呈现Markdown。
我的问题是我想动态加载降价文件,而不是用import. 场景是这发生在文章详细信息页面上,即我articleId从路由参数中获取,然后基于该 ID,我想加载相应的降价文件,例如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
Run Code Online (Sandbox Code Playgroud)
这可以正常工作,但是如果我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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2632 次 |
| 最近记录: |