在带有React的ASP.NET Core App中包含图像

时间:2018-10-09 19:29:13

标签: asp.net reactjs

我有一个运行在ASP.NET Core服务器上的React应用。

我正在尝试在我的一个反应页面上显示图像。 (图像位于:“ project_folder / ClientApp / src / images / progress_bar.gif”)

但这都不起作用:

<img alt="loading..." src={'./progress_bar.gif'} />
<img alt="loading..." src={'images/progress_bar.gif'} />
<img alt="loading..." src={'./images/progress_bar.gif'} />
<img alt="loading..." src={'require(./images/progress_bar.gif')} />

我什至试图禁用它:

app.UseStaticFiles();

仍然没有运气。但是我可以通过CSS加载文件,而不会出现类似问题:

background-image: url("./images/login-left.jpg");

这会产生类似https://localhost:44329/static/media/login-left.270403e0.jpg

2 个答案:

答案 0 :(得分:1)

尝试以下选项。这是在React中导入图像的两种方法。 require的原因对您不起作用,因为您已在引号中添加了require,因此该字符串不应该使用引号。确保您的路径正确。如果您的路径正确,则可以使用以下选项

 import progressBar from '../images/progress_bar.gif';

   <img alt="loading..." src={progressBar} />

  <img alt="loading..." src={require('../images/progress_bar.gif')} />

答案 1 :(得分:0)

对于Webpack,使用静态资源(如图像和字体)的工作方式与CSS相似。

您可以直接在TypeScript模块中 import文件。这告诉Webpack将文件包含在捆绑软件中。与CSS导入不同,导入文件会为您提供一个字符串值。此值是您可以在代码中引用的最终路径。

要减少对服务器的请求数量,导入小于10,000字节的图像将返回data URI而不是路径。这适用于以下文件扩展名:bmp,gif,jpg,jpeg和png。由于#1153,SVG文件被排除在外。

开始之前,您必须将每种资产类型定义为有效的模块格式。否则,TypeScript编译器将生成如下错误:

  

找不到模块'./logo.png'。

要在TypeScript中导入资产文件,请在您的项目中创建一个新的类型定义文件,并将其命名为 assets.d.ts 。然后,为您需要导入的每种资产类型添加一行:

declare module "*.gif";
declare module "*.jpg";
declare module "*.jpeg";
declare module "*.png";
declare module "*.svg";

在这种情况下,我们添加了几个图像文件扩展名作为有效的模块格式。现在已经配置了编译器,下面是导入图像文件的示例:

import React from 'react';
import logo from './logo.svg'; // 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;

Adding Images, Fonts, and Files的完整参考