React.js从公共文件夹加载图像不起作用

时间:2020-11-01 20:05:56

标签: reactjs react-native

我目前正在学习React.js,我想从公共文件夹中加载图像。但是由于某些原因,这是行不通的。 我的配置如下所示: enter image description here

我要在其中显示图像的组件看起来像这样:

import React, {useState, useEffect} from "react";
import Tile from "../../../Tiles/Tile/Tile";
import './../../../Tiles/Tiles.sass';

function Market() {

    return (
        <>
            <h1>Market</h1>
            <div className="Tiles__Container">
                <Tile src="Images/img-1.jpg"/>
            </div>

        </>
    );
}

export default Market;

我正在调用的组件:

import React from "react";
import {Link} from "react-router-dom";

function Tile(props) {
    return (
        <div className="Tiles__Item">
            <Link className="Tiles__Item__Link" to={props.path}>
                <figure className="Tiles__Item__Pic-Wrap" data-category={props.label}>
                    <img className="Tiles__Item__Img" src="Images/img-1.jpg" alt={props.label}/>
                </figure>
                <div className="Tiles__Item__Info">
                    <h5 className="Tiles__Item__Text">{props.text}</h5>
                    <h6 className="Tiles__Item__Text">{props.perAmount}</h6>
                </div>
            </Link>
        </div>
    );
}

export default Tile;

当我查看更改时,它看起来像这样: enter image description here

如果我查看开发者控制台,则会从此处加载图像: enter image description here

这是错误的,位置应如下所示: http:// localhost:3001 / Images / img-1.jpg

您的 西马格多

2 个答案:

答案 0 :(得分:0)

导入图像并以这种方式使用

import React, {useState, useEffect} from "react";
import Tile from "../../../Tiles/Tile/Tile";
import './../../../Tiles/Tiles.sass';
import img1 from '../../../../../public/Images/img-1.jpg'; // Here we are importing the image directly

function Market() {

    return (
        <>
            <h1>Market</h1>
            <div className="Tiles__Container">
                <Tile src={img1}/>
            </div>

        </>
    );
}

export default Market;

在组件中,我们将img1作为src属性传递给我们,所以让我们使用它

import React from "react";
import {Link} from "react-router-dom";

function Tile(props) {
    return (
        <div className="Tiles__Item">
            <Link className="Tiles__Item__Link" to={props.path}>
                <figure className="Tiles__Item__Pic-Wrap" data-category={props.label}>
                    <img className="Tiles__Item__Img" src={props.src} alt={props.label}/>
                </figure>
                <div className="Tiles__Item__Info">
                    <h5 className="Tiles__Item__Text">{props.text}</h5>
                    <h6 className="Tiles__Item__Text">{props.perAmount}</h6>
                </div>
            </Link>
        </div>
    );
}

export default Tile;

答案 1 :(得分:0)

谢谢您的反馈,问题是我在尝试以这种方式加载图像时遇到以下错误:

./src/components/Pages/Shops/Market/Market.js
Module not found: You attempted to import ../../../../../public/Images/img-1.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

此外,我想在该页面上显示很多图像,但是现在,我只想使用一个图像来查看它是否有效。