我关注了这篇文章,要求将图像添加到我未弹出的Webpack create-react-app中:React won't load local images
没有上述情况,则会引发错误。
问题在于,在映射函数中执行此操作时会崩溃:
const ThumbNail = styled.img`
border: 2px dotted blue;
`;
export default props => {
const images = [
'../images/dragonglass_pendant.jpg',
'../images/dragonglass_pendant2.jpg',
'../images/dragonglass_pendant3.jpg',
];
return (
<React.Fragment>
{
images.map(imageSrc => {
console.log(imageSrc, `=====imageSrc=====`);
return <ThumbNail src={require(imageSrc)} />
})
}
</React.Fragment>
)
}
// Chrome browser console
../images/dragonglass_pendant.jpg =====imageSrc=====
ImageThumbnails.jsx:25 ../images/dragonglass_pendant.jpg =====imageSrc=====
catalog sync:2 Uncaught Error: Cannot find module '../images/dragonglass_pendant.jpg'
at webpackEmptyContext (eval at ./src/catalog sync recursive (main.chunk.js:55), <anonymous>:2:10)
at eval (ImageThumbnails.jsx:26)
at Array.map (<anonymous>)
at eval (ImageThumbnails.jsx:24)
at renderWithHooks (react-dom.development.js:13354)
at mountIndeterminateComponent (react-dom.development.js:15407)
at beginWork (react-dom.development.js:16042)
我也尝试过不要求。失败
我也尝试过在顶部使用import关键字。此方法有效,但删除了程序化图像导入(图像必须基于API调用数据导入)
有人知道为什么当映射到上方时require会突破吗?
编辑:使用import关键字代替require,对于每个图像我都会得到相同的错误:
catalog lazy groupOptions: {} namespace object:5 Uncaught (in promise) Error: Cannot find module '../images/dragonglass_pendant.jpg'
at eval (eval at ./src/catalog lazy recursive (main.chunk.js:55), <anonymous>:5:11)
答案 0 :(得分:0)
const images = [
'./images/dragonglass_pendant.jpg',
'./images/dragonglass_pendant2.jpg',
'./images/dragonglass_pendant3.jpg',
];
export default () => (
<React.Fragment>
{images.map((image, idx) => <img key={idx} src={require(`${image}`) />)}
</React.Fragment>
)
在此示例中,图像必须位于src文件夹中 。它对我有用
答案 1 :(得分:0)
通过将require语句移至数组中来解决,如下所示:Require(img path) not working/ cannot find module "." reactjs
const images = [
require("../images/dragonglass_pendant.jpg"),
require("../images/dragonglass_pendant2.jpg"),
require("../images/dragonglass_pendant3.jpg"),
]