简体   繁体   English

React - 从远程服务器加载图像(绝对路径需要/导入)?

[英]React - loading images from a remote server (absolute path require/import)?

I'm using a React plugin that processes all of my images, and it allows for two types of loading data.我正在使用一个 React 插件来处理我的所有图像,它允许两种类型的加载数据。

// Approach 1 - working
<img src={require('./images/my-image.jpg')} />

// Approach 2 - working
import MyImage from './images/my-image.jpg';

<img src={MyImage} />

Both approaches work fine, but the problem I'm facing is:两种方法都可以正常工作,但我面临的问题是:

  • I'm getting my images in a response,我收到了我的图片作为回应,
  • they're stored on separate server.它们存储在单独的服务器上。

I've tried hardcoding to see if remote server would work and it does not:我已经尝试硬编码以查看远程服务器是否可以工作,但它不能:

// Approach 1 - ModuleNotFoundError: Module not found: Error: Can't resolve url
<img src={require('http://example.com/images/my-image.jpg')} />

// Approach 2 - ModuleNotFoundError: Module not found: Error: Can't resolve url
import MyImage from 'http://example.com/images/my-image.jpg';

<img src={MyImage} />

How do I tackle this?我该如何解决这个问题? Can I even require('http://absolute-address.domain')?我什至可以要求('http://absolute-address.domain')吗? Don't really know where to look for require documentation when it comes to React, can't find it anywhere in the docs.当涉及到 React 时,真的不知道在哪里寻找require的文档,在文档中的任何地方都找不到它。

Can you just use <img src='http://example.com/images/my-image.jpg'/> ?你可以使用<img src='http://example.com/images/my-image.jpg'/>吗?

Require and import are both used for loading dependencies locally in Node, so I don't think they'd apply here. Require 和 import 都用于在 Node 中本地加载依赖项,所以我认为它们不会在这里应用。 You could either save the images locally and then require them, or reference an external URL.您可以将图像保存在本地然后require它们,或者引用外部 URL。

this works.这行得通。

const path='http://example.com/images/my-image.jpg';

<img src={path} />

require is used for function imports or react components. require 用于 function 导入或反应组件。

import MyImage from './images/my-image.jpg'; means import the proper url of './images/my-image.jpg'.表示导入“./images/my-image.jpg”的正确 url。 Which may relate to how build tool package the app and what base path you set.这可能与如何构建工具 package 应用程序以及您设置的基本路径有关。

Now since you have a absolute url path of the image, why don't use it directly?现在既然有了图片的绝对url路径,为什么不直接使用呢?

<img src="http://example.com/images/my-image.jpg" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM