使用require()从相对路径加载图像时无法找到模块

问题描述 投票:0回答:2

我试图从反应组件的状态给出的路径加载图像。使用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
reactjs react-router
2个回答
0
投票

使用导入来加载图像它将解决您的问题。

import imgOne from '../assets/images/img-1.jpg'; 

<img src={imgOne}/>

0
投票

问题解决了。这是因为我在src文件夹中的每个文件夹都有一个index.js文件。 webpack和react-create-app的默认路径解析器构造一个数组相对路径,并在执行此操作时,它在cwd中搜索index.js文件,如果找到,则将所有相对路径映射到此目录或其直接父级。因此,../或./将映射到当前工作目录中的路径。我把资产文件夹移到cwd里面,问题解决了。虽然这只是一种解决方法,但我相信这是一个更好的权衡,可以浪费时间来试图找出webpack或react-create-app锅炉板代码的内部结构。

感谢大家的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.