你不能使用 ES6 导入来做到这一点,因为它们是静态的。
这意味着您必须在编译时指定导入和导出的内容,并且无法在运行时对更改做出react。
使用数组之类的东西意味着代码必须运行,然后系统才能自信地知道要导入的内容。
当前*(见下文)解决此问题的唯一方法是使用require
CommonJS方法。
const routes = Array
.from({ length: 10 }) // create array of 10 elements
.map((_, i) => require(`../samples/sample${i + 1}`)) // map each element to an imported file using the index
.map((c, i) => ( // map each component to a route
<Route
path={`/sample${i + 1}`}
component={c}
/>
))
您还可以将两个map
循环合二为一:
const routes = Array
.from({ length: 10 })
.map((c, i) => (
<Route
path={`/sample${i + 1}`}
component={require(`../samples/sample${i + 1}`)}
/>
))
话虽如此,但更有可能不是,您可能不需要 10 个不同的样本组件。与其为微小的差异创建单独的组件,为什么不使用单个组件并将其传递给确定其行为的类型呢?
import Sample from './sample'
const routes = Array
.from({ length: 10 }) // create array of 10 elements
.map((c, i) =>
<Route // map each component to a route
path={`/sample${i + 1}`}
component={props => <Sample type={i + 1} {...props} />}
{/* ^ now every sample knows which one it is */}
/>
)
事实上,您可能也不需要多条路线,并且可以使用带有代表样本类型的动态段的单路线,并将其传递给组件。
import Sample from './sample'
<Route path="/sample/:type" component={({ params }) => <Sample type={params.type} />} />
目前有一个提议是在 ES6 module中添加动态导入:
Promise.all(
Array
.from({ length: 10 }) // create array of 10 elements
.map((_, i) => import(`../samples/sample${i + 1}`)) // map each element to a promise resolving to the imported file
).then(components => { // map each component to a route
const routes = components
.map((c, i) => (
<Route
path={`/sample${i + 1}`}
component={c}
/>
))
})