Javascript 使用img标记react时无法使用相对路径

Javascript 使用img标记react时无法使用相对路径,javascript,reactjs,image,path,Javascript,Reactjs,Image,Path,我有一个img标记,当我为我的React项目使用相对src路径时,它没有加载我想要的图像。 当我这样做时: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebase.js"; import "./LobbyStyle.css"; import pfp2 from "./images/pfp2.png&q

我有一个img标记,当我为我的React项目使用相对src路径时,它没有加载我想要的图像。 当我这样做时:

//import { ReactComponent } from '*.svg';
import React from 'react';
import firebase from "./firebase.js";
import "./LobbyStyle.css";
import pfp2 from "./images/pfp2.png"

class ImgButton extends React.Component {

    constructor(props){
        super();
    }

    render(props){
        return (<button style = {{backgroundColor : "rgba(0,0,0,0)", borderColor: "rgba(0,0,0,0)"}}><img src = {pfp2} onClick = {this.props.onClick}/></button>)
    }
}

class ImgRow extends React.Component {

    render(){
        var iconlist = this.props.images.map(image => 
            <div key = {image} >
                <ImgButton onClick = {this.props.onClick} img = {image}/>
            </div>
        )
        return(
            <div style={{display: "flex"}}>
                {iconlist}
            </div>
        )
    }
}

export default ImgRow;
//从'*.svg'导入{ReactComponent};
从“React”导入React;
从“/firebase.js”导入firebase;
导入“/LobbyStyle.css”;
从“/images/pfp2.png”导入pfp2
类ImgButton扩展了React.Component{
建造师(道具){
超级();
}
渲染(道具){
返回()
}
}
类ImgRow扩展了React.Component{
render(){
var iconlist=this.props.images.map(image=>
)
}
}
类ImgRow扩展了React.Component{
render(){
var iconlist=this.props.images.map(image=>
)
返回(
{iconlist}
)
}
}
出口增长;

我做错了什么?是否需要导入我的图像?这是我的文件路径,如您所见,我相信相对路径是正确的,因为images文件夹与我的代码位于同一文件夹中: 答案是

大多数React应用程序将使用Webpack、Rollup或Browserify等工具“捆绑”文件绑定是跟踪导入的文件并将其合并为单个文件的过程:“绑定”。然后可以将此捆绑包包含在网页中,以便一次加载整个应用程序。

当您的react应用程序捆绑在一起时,所有导入的资产(如您的图像)都被捆绑在一起。相对图像路径没有任何意义,因为该路径不存在于作为react应用程序加载到网页上的捆绑代码和资产的上下文中


导入映像是正确的做法。

您可以对内联映像src使用require

<img src = {require('./images/pfp2.png')} onClick = {this.props.onClick}/>

<img src = {require('./images/pfp2.png')} onClick = {this.props.onClick}/>