【问题标题】:Error: Cannot find module './' When importing images in React?错误:在 React 中导入图像时找不到模块“./”?
【发布时间】:2020-10-29 22:05:15
【问题描述】:

我正在从 .json 中提取一些数据,以在我正在开发的 react 应用程序中传播网格。

{props.title} 和 {props.author} 正在正确返回,但我无法显示图像。目前我在前往这条路线时登陆“错误:找不到模块'./'”页面。

我确信它是我指向 /assets/images 的文件路径,但无法解决。

这是我的文件路径:

```
src
 ┣ assets
 ┃ ┗ images
 ┃ ┃ ┣ burger-logger.png
 ┃ ┃ ┗ green_cup.png
 ┣ components
 ┃ ┣ About
 ┃ ┃ ┣ About.js
 ┃ ┃ ┣ Hello.js
 ┃ ┃ ┗ index.scss
 ┃ ┣ PortfolioGrid
 ┃ ┃ ┣ PortfolioGrid.js
 ┃ ┃ ┗ tileData.js
 ┃ ┣ Header.js
 ┃ ┗ Hero.js
 ┣ pages
 ┃ ┣ Home
 ┃ ┃ ┣ index.js
 ┃ ┃ ┗ style.css
 ┃ ┗ Portfolio
 ┃ ┃ ┗ index.js
 ┣ App.js
 ┣ index.css
 ┣ index.js
 ┗ projects.json
```

这是网格组件 -

```
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import ListSubheader from '@material-ui/core/ListSubheader';
import IconButton from '@material-ui/core/IconButton';
import InfoIcon from '@material-ui/icons/Info';
import Projects from '../../projects.json';
import '../../assets/images/burger-logger.png';

const useStyles = makeStyles((theme) => ({...

/**
 
export default function PortfolioGrid(props) {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <GridList cellHeight={180} className={classes.gridList}>
        <GridListTile key="Subheader" cols={2} style={{ height: 'auto' }}>
          <ListSubheader component="div"></ListSubheader>
        </GridListTile>
        {Projects.map((props) => (
          <GridListTile key={props.image}>
            <img src={require(`../../assets/images/${props.image}`)} alt={props.title} />
            <GridListTileBar
              title={props.title}
              subtitle={<span>by: {props.author}</span>}
              actionIcon={
                <IconButton aria-label={`info about ${props.title}`} className={props.icon}>
                  <InfoIcon />
                </IconButton>
              }
            />
          </GridListTile>
        ))}
      </GridList>
    </div>
  );
}
```

这是 .json 结构 -

```
[
  {
    "id": 1,
    "title": "Burger-Logger",
    "image": "burger-logger.png",
    "author": "Me"
  },
  {
    "id": 2,
    "title": "test",
    "image": "",
    "author": "Me"
  }
]
```

对不起,文字墙。任何方向都非常感谢。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    试试这个

    <img src={require(`../assets/images/${props.image}.png`)}/>
    

    【讨论】:

    • 奇怪的是,这给了我这个错误:“错误:找不到模块'./burger-logger.png.png'”。在添加您的建议之前,错误是:“错误:找不到模块'./'”
    • 那../assets/images/burger-logger.png)}/>
    • 您的建议有效。我删除了图像并获得了新的屏幕截图,以确保我在第一次命名文件时没有做任何愚蠢的事情。迷失了模板文字没有给出正确文件路径的方式
    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2022-10-06
    相关资源
    最近更新 更多