我正在使用 create-react-app 和 react-router 创建一个反应应用程序。我想获取我的 React 应用程序的根 URL 路径,因为它可以在不同的位置提供:
不同页面的链接不受这种差异的影响,因为 react-router 根据 react 根路径处理 to-location。实际上,我的图像存储在公共路径中,因此,我可以在基本位置访问它:/<page>
<img src={images/example.png}>
Run Code Online (Sandbox Code Playgroud)
但是如果我在子页面中或者只是 URL 以“/”结尾,例如 /<page>/
<img src={images/example.png}>
Run Code Online (Sandbox Code Playgroud)
将无法工作,因为浏览器搜索图像/<page>/images/example.png而不是/images/example.png。此外,如果我将图像 src 设置为/images/example.png它仅适用于本地主机而不适用于生产,因为在生产中,浏览器会搜索图像example.com/images/example.png而不是example.com/interface/images/example.png
这就是为什么我需要获取 react 根 URL 路径的原因。例如,它允许我在本地主机中获取“/”和在生产中获取“/interface/”
感谢您的帮助