我在我的react项目上的图像有一些问题。事实上,我一直认为src属性的相对路径是建立在文件体系结构上的

下面是我的文件架构:

components
    file1.jsx
    file2.jsx
    file3.jsx
container
img
js 
... 

然而,我意识到路径是建立在url上的。在我的一个组件(例如file1.jsx)中,我有这个:

localhost/details/2
<img src="../img/myImage.png" /> -> works

localhost/details/2/id
<img src="../img/myImage.png" /> -> doesn't work, images are not displayed

怎么解决这个问题呢?我想在任何形式的路由处理的react-router,所有的图像可以显示相同的路径。


当前回答

我用过这种方法,效果很好

import Product from "../../images/product-icon.png";
import { Icon } from "@material-ui/core";

<Icon>
    <img src={Product} style={{ width: "21px", height: "24px" }} />
</Icon>

其他回答

在组件中导入图像

import RecentProjectImage_3 from '../../asset/image/recent-projects/latest_news_3.jpg'

并在image src={RecentProjectImage_3}上调用图像名称作为对象

 <Img src={RecentProjectImage_3} alt="" />

根据webpack.config.js的官方使用指令,添加文件加载器npm,如下所示:

config.module.rules.push(
    {
        test: /\.(png|jpg|gif)$/,
        use: [
            {
                loader: 'file-loader',
                options: {}
            }
        ]
    }
);

为我工作。

我用create-react-app创建了我的应用程序,如果我想动态改变我的image src,我使用require指令:

export const MyComponent = () => {
  const [myImg, setMyImg] = useState(require('./path/to/my/img'));

  const handleClick = () => {
    setMyImg(require('./path/to/other/img'));
  }

  return (
    <div>
      <img src={myImg} alt='myImg' />
      <button onClick={handleClick}>Click me!<button/>
    <div>
  )
}

如果图像放在src文件夹中,请使用以下方法:

<img src={require('../logo.png')} alt="logo" className="brand-logo"/>

在create-react-app中有一个公共文件夹(index.html…) 如果你把“myImage.png”放在img子文件夹下,你可以通过以下方式访问:

<img src={window.location.origin + '/img/myImage.png'} />