创建一个循环以在React中动态导入文件 [英] Create a loop to import files dynamically in React

查看:33
本文介绍了创建一个循环以在React中动态导入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下,我有一个包含 .md 文件的文件夹,如下所示:

Consider I have a folder with .md files like this:

/static/blog/
  example_title.md
  another_example.md
  three_examples.md

我有一个包含所有标题的数组:

and I have an array including all titles:

const blogEntries = ["example_title", "another_example", "three_examples"]

在我的组件中,我要全部导入,请注意可能会更少或更多.

in my component I want to import all of them, notice that there could be fewer or more.

有什么办法可以动态导入它们,类似于:

Is there any way to dynamically import them similar to:

for (let entry in blogEntries) {
  import `Markdown_${entry}` from `/static/blog/${entry}.md`
}

,然后在我的渲染器中可以执行以下操作:

and later in my render I can do:

<Markdown_three_examples />

以上内容显然行不通,但我正在寻找一种实现类似目的的方法.

the above obviously would not work, but I'm looking for a way to achieve similar.

推荐答案

您可以尝试使用

You can try to use dynamic imports - import(). As the time implies, they work during runtime, and can have dynamic urls.

注意:目前,Chrome和Safari浏览器原生支持它们 ,但不是通过Firefox,IE和Edge来实现的.但是,您可以使用webpack解决该问题.

Note: currently they are supported natively by Chrome and Safari, but not by firefox, IE, and Edge. However, you can use webpack to solve that.

const blogEntries = ["example_title", "another_example", "three_examples"]

const loadEntries = (entries) =>
  Promise.all(entries.map((entry) => import(`/static/blog/${entry}.md`)));

loadEntries(blogEntries)
  .then((entries) => console.log(entries));

这篇关于创建一个循环以在React中动态导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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