javascript - React依赖模块正在父模块中寻找图像源

标签 javascript reactjs

我有一个 footer React 模块,它将作为依赖项安装在其他几个项目中。

当尝试在 footer 模块内使用图像元素时,它会尝试在父模块中而不是在其自己的 /resources/img 文件夹中查找图像源。

下面是代码片段。

<img className="footer-dropdown" src="/resources/img/footer_arrow_default.svg"/>

最佳答案

如果您的项目使用 CRA 引导,则需要导入镜像。

See adding images in CRA :

With webpack, using static assets like images and fonts works similarly to CSS.

You can import a file right in a JavaScript module. This tells webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.

对于图像路径:

import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}
export default Header;

至于渲染 svg:

import { ReactComponent as Logo } from './logo.svg';
function App() {
  return (
    <div>
      {/* Logo is an actual React component */}
      <Logo />
    </div>
  );
}

关于javascript - React依赖模块正在父模块中寻找图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60882257/

相关文章:

wordpress - 在现有的 WordPress 网站上使用react

reactjs - 如何重置嵌套导航器 (react-navigation v5)

javascript - 为什么下划线与其类型检查不一致?

JavaScript 破折号抛出 ReferenceError

javascript - 如何根据另一个节点中的数据对 Firebase 数组进行排序?

javascript - 在react应用程序中使用react-test-renderer和storybook执行组件测试时出错

javascript - JSPLUMB:在特定用户交互后禁用节点拖放

javascript - 当哈希值未更改时异步 onHashChange 触发

javascript - 在 react 中显示 JSON

javascript - 将 React 上下文恢复到默认状态