Dar*_*ll 6 javascript dynamic-import web reactjs webpack
在网上看到了几个答案,但没有明确的解释,解决方案也不起作用。所以这就是我想要做的:
src/assets/images文件夹下这是我目前的实现方式(不起作用):
// for example
const imageList = ['img1', 'img2', 'img3' /*...so on */]
const getImagePath = (image) => {
return `../assets/images/${image}.jpg`
}
function ImagesPage() {
return (
<>
<p>Below should show a list of images</p>
{imageList.map((img) => {
return <img src={require(getImagePath(img))} />
})}
</>
)
}
Run Code Online (Sandbox Code Playgroud)
从我在线阅读的内容来看,这与webpack 的工作方式有关,并且只有在将确切的字符串路径输入到以下内容时才会起作用require:
// This works:
<img src={require('../assets/images/img1.jpg')} />
// But all these will not work:
<img src={require(getImagePath(img))} />
const img = 'img1.jpg'
<img src={require(`../assets/images/${img}`)} />
Run Code Online (Sandbox Code Playgroud)
知道如何让这种动态导入图像在我上面描述的场景中工作吗?我认为这篇文章对其他寻找答案的人也会很有帮助。
mle*_*ter 11
添加 .default 即可解决问题
<img src={require(`../../folder-path/${dynamic-filename}.png`).default} />
Run Code Online (Sandbox Code Playgroud)
太长了;
// All of these works
const fileNameExt = 'foo.jpg'
<img src={require('../images/' + fileNameExt)} />
<img src={require(`../images/${fileNameExt}`)} />
const fileName = 'foo'
<img src={require('../images/' + fileName + '.jpg')} />
<img src={require(`../images/${fileName}.jpg`)} />
// These does not work:
const myPathVariable1 = '../images/' + 'foo' + '.jpg'
<img src={require(myPathVariable1)} />
const myPathVariable2 = '../images/' + 'foo.jpg'
<img src={require(myPathVariable2)} />
Run Code Online (Sandbox Code Playgroud)
文件名:
const imageList = ["img1", "img2", "img3", ... ]
Run Code Online (Sandbox Code Playgroud)
并在 UI 上渲染(添加目录路径和内部扩展require名):
{
imageList.map(img => {
return <img src={require("../assets/images/" + img + ".jpg")} />
})
}
Run Code Online (Sandbox Code Playgroud)
为什么它有效?:
Webpack 可以通过生成有关目录和扩展的上下文来理解这个表达式,并可以加载所有匹配的模块。
更新您的getImagePath函数以返回一个img元素。
const getImage = (image) => {
return <img src={require(`../assets/images/${image}.jpg`)} />
}
Run Code Online (Sandbox Code Playgroud)
那么你的map函数将如下所示:
imageList.map((img) => {
return getImage(img);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3924 次 |
| 最近记录: |