【问题标题】:Problems with loading image directly onto index.html in create-react-app在 create-react-app 中将图像直接加载到 index.html 的问题
【发布时间】:2019-11-23 07:28:19
【问题描述】:

我希望有一个完整的 html 页面,然后是一个使用 React 的小部分。我知道有比使用 create-react-app 更好的方法来做到这一点,但目前这就是我正在使用的。文件目录是这样的。

public
    index.html 
src
    assets
        images
            logo.png

    components 
    index.js
    index.css

除了在 header 标记内添加内容外,我并没有触及很多原始 index.html。 我希望在 HTML 中显示图片,但目前只显示替代文本。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <meta name="description" content="Web site created using create-react-app" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lobster+Two:100,300,400,700,900">
  <link rel="apple-touch-icon" href="logo192.png" />
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
  <title>My website</title>
</head>

<body>
  <header class="header">
    <div class="logo-box">
      // I cannot display the image at this part, I am pretty sure the link is correct.
      <img src="/mywebsite/src/assets/images/logo.png" alt="Logo" class="logo"> 
    </div>
  </header>

  <div id="root"></div> // react section will go here
</body>
</html>

【问题讨论】:

  • 您能否提供您遇到的错误以及您想要实现的目标。
  • 没有错误,图片根本不显示,只显示alt文本。我只想将图像添加到标题标签中并让它显示在 HTML
  • 如果您使用的是 chrome,您可以打开开发者工具并右键单击 img 标签的来源并在新标签页中打开它,这将帮助您确定链接是否正确。
  • 它仍然显示替代文本而不是徽标

标签: html css reactjs create-react-app


【解决方案1】:

您是否尝试在运行 npm start 时显示图像?如果是这样,您需要将资产移动到公用文件夹中,然后在 localhost 中引用它们。

参考:https://create-react-app.dev/docs/using-the-public-folder

如果您计划在构建代码时捆绑和部署资产,我建议您通读https://webpack.js.org/guides/asset-management/,因为 create-react-app 默认使用 webpack 进行部署。

【讨论】:

  • 您是否将资产移动到公用文件夹并尝试使用相对路径进行引用?
  • 我的 index.css 文件当前引用了来自 src/assets/images 的一些图像,因此这意味着我可能还必须创建 public/images .. 让它变得非常混乱。也许我会研究 webpack
  • 你的建议可行,希望我暂时不需要接触 webpack,看起来很复杂哈哈
猜你喜欢
  • 2019-05-15
  • 2020-04-14
  • 2018-02-11
  • 2021-10-28
  • 1970-01-01
  • 2018-09-21
  • 2020-08-27
  • 2018-03-22
  • 1970-01-01
相关资源
最近更新 更多