在 React 应用程序中定义图像路径时遇到问题

Having issue with defining path for image in a react application

我在 React 应用程序中定义图像路径时遇到问题,这让我很沮丧,所以我正在寻求专业人士的帮助。我正在 public 和 src 之间来回移动我的图像文件夹。当 background:url(path) 有效时,img src="path" 无效并且 vice-versa。我收到此错误“错误:无法解析‘/Applications/MAMP/htdocs/react-web/src’中的 'images/img-2.jpg'”。如果我将图像文件夹移动到 src,它可以工作,但 background:url(path) 不会加载图像。我在 https://github.com/miraj977/react-project/. Another issue is github pages; I have setup this project in gh-pages (https://miraj977.github.io/react-project/) 中有项目,但它只加载到导航并停止。不加载 body。另外,我在 package.json "https://miraj977.github.io/react-project/" 中设置了主页,但每当我单击应重定向到主页的徽标时,它都会重定向到 "https:// miraj977.github.io/”。我已将 link 共享到 github 项目,供您查看代码。现在越来越郁闷了。请指导我以正确的方式解决这些问题。非常感谢您的宝贵时间。提前谢谢你。

只有显示的导航栏实际上与您的路由配置有关。

而不是这个:

function App() {
  return (
    <>
      <Router>
        <Navbar />
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/services" exact component={Services} />
          <Route path="/products" exact component={Products} />
          <Route path="/sign-up" exact component={SignUp} />
        </Switch>
      </Router>
    </>
  );
}

这样做:

function App() {
  return (
    <>
      <Router>
        <Navbar />
        <Switch>
          <Route path="/react-project" exact component={Home} />
          <Route path="/react-project/services" exact component={Services} />
          <Route path="/react-project/products" exact component={Products} />
          <Route path="/react-project/sign-up" exact component={SignUp} />
        </Switch>
      </Router>
    </>
  );
}

由于您的主页 url 带有 /react-project 后缀,您需要在路由和重定向中考虑到这一点。


因此,为了更加清晰,您 Navbar 中的导航 Link 组件也应更改为:

<Link to="/" className="navbar-logo" onClick={closeMobileMenu}>
  1 TRVL 2 <i class="fab fa-typo3" />3{" "}
</Link>

对此:

<Link to="/react-project" className="navbar-logo" onClick={closeMobileMenu}>
  1 TRVL 2 <i class="fab fa-typo3" />3{" "}
</Link>

至于图像问题

要通过 src 指定 img,您可以这样做:

import img1 from "../images/img-1.jpg"; // relative path from directory this component file is in
// ...

<CardItem
  src={img1}
  text="Explore the hidden waterfall deep inside the Amazon Jungle"
  label="Adventure"
  path="/services"
/>

要通过 css 将图像指定为背景图像,您可以这样做:

background: url("../images/img-home.jpg"); // Also relative to current file location

来自 public url 的路径显然不再像在 create React app 4 中那样解析,参见 this github issue