我正在尝试从反应组件状态下给出的路径加载图像。使用由 create-react-app 创建的应用程序。得到以下错误:
找不到模块“../assets/images/img-2.jpg”
已检查图像是否存在于路径上。此外,这仅发生在安装 react-router-dom 并设置路由之后。
import React, {Component} from 'react';
import { Carousel,Image } from 'react-bootstrap';
class JumboBanner extends Component {
constructor(props, context) {
super(props, context);
this.handleSelect = this.handleSelect.bind(this);
this.state = {
index: 0,
direction: null,
images : [
{path:'../assets/images/img-1.jpg', body:{title:'This is title',text:'Kutchi Text'}},
{path:'../assets/images/img-2.jpg', body:{title:'This is title',text:'Kutchi Text'}},
]
};
}
handleSelect(selectedIndex, e) {
this.setState({
index: selectedIndex,
direction: e.direction,
});
}
render() {
const { index, direction,images } = this.state;
const corouselItems = images.map(img=> (<Carousel.Item>
<Image className="d-block w-100" src={require(`${img.path}`)}/>
{/* <img
className="d-block w-100"
src={require(`${img.path}`)}
alt="First slide"
/> */}
</Carousel.Item>) );
return (
<Carousel
activeIndex={index}
direction={direction}
onSelect={this.handleSelect}>
{corouselItems}
</Carousel>
);
}
}
export default JumboBanner;
-testapp
|-public
|-src
|--assets
|-|-images
问题解决了。这是因为我在 src 文件夹中的每个文件夹都有一个 index.js 文件。webpack 和 react-create-app 的默认路径解析器构造了一个数组相对路径,在执行此操作时,它会在 cwd 中搜索 index.js 文件,如果找到,则将所有相对路径映射到该目录或其直接父目录。因此, ../ 或 ./ 将映射到当前工作目录中的路径。我将资产文件夹移动到 cwd 中,问题解决了。虽然这只是一种解决方法,但我相信它可以更好地权衡浪费时间试图找出 webpack 或 react-create-app 样板代码的内部结构。
谢谢大家的帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句