我在我的React项目中遇到了一些关于图片的问题。事实上,我一直以为src属性中的相对路径是基于文件的架构来构建的。
这是我的文件架构:
components
file1.jsx
file2.jsx
file3.jsx
container
img
js
...
然而,我意识到路径是基于URL来构建的。在我的一个组件中(例如file1.jsx),我有以下代码:
localhost/details/2 <img src="../img/myImage.png" /> -> 正常工作 localhost/details/2/id <img src="../img/myImage.png" /> -> 不工作,图片无法显示
如何解决这个问题?我希望在由react-router处理的任何路由形式中,所有图片都能以相同的路径显示。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在
create-react-app中,似乎无法使用相对路径来引用图片。相反,你可以使用import来引入图片:import logo from './logo.png' // 图片的相对路径 class Nav extends Component { render() { return ( <img src={logo} alt={"logo"}/> ) } }