React.js:映射时需要图像失败
2019-02-27
317
我按照这篇文章将图像导入未弹出的 create-react-app 以供 Webpack 使用: React 不会加载本地图像
如果没有上述内容,则会引发错误。
问题是,在映射函数中执行此操作时,它会崩溃:
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)
2个回答
通过将 require 语句移到数组中来解决,如下所示: Require(img path) 不起作用/找不到模块“。” reactjs
const images = [
require("../images/dragonglass_pendant.jpg"),
require("../images/dragonglass_pendant2.jpg"),
require("../images/dragonglass_pendant3.jpg"),
]
Sean D
2019-02-27
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 文件夹中 。它对我有用
Bonjov
2019-02-27