动态添加图片 React Webpack [英] Dynamically Add Images React Webpack

查看:38
本文介绍了动态添加图片 React Webpack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究如何通过 React 和 Webpack 动态添加图像.我在 src/images 下有一个图像文件夹,在 src/components/index 下有一个组件.我正在使用带有以下 webpack 配置的 url-loader

I've been trying to figure out how to dynamically add images via React and Webpack. I have an image folder under src/images and a component under src/components/index. I'm using url-loader with the following config for webpack

    {
      test: /.(png|jpg|)$/,
      loader: 'url-loader?limit=200000'
    }

在组件内我知道我可以在创建组件之前为文件顶部的特定图像添加 require(image_path) 但我想让组件通用并让它具有属性带有从父组件传递的图像的路径.

Within the component I know I can add require(image_path) for a specific image at the top of the file before I create the component but I want make the component generic and have it take a property with the path for the image that is passed from the parent component.

我尝试过的是:

<img src={require(this.props.img)} />

对于实际属性,我已经尝试了几乎所有我能想到的从项目根目录、react 应用程序根目录和组件本身到图像的路径.

For the actual property I have tried pretty much every path I can think of to the image from the project root, from the react app root, and from the component itself.

文件系统

|-- src
|   ` app.js
|   `--images
|      ` image.jpg
|      ` image.jpg
|   `-- components
|      `parent_component.js
|      `child_component.js

父组件基本上只是一个容纳多个子组件的容器,所以...

The parent component is basically just a container to hold multiples of the child so...

<ChildComponent img=data.img1 />
<ChildComponent img=data.img2 />
etc....

有什么方法可以使用带有 url-loader 的 react 和 webpack 来做到这一点,还是我只是走错了路来解决这个问题?

Is there any way in which to do this using react and webpack with url-loader or am I just going down a wrong path to approach this?

推荐答案

使用 url-loader,描述在这里 (SurviveJS - 加载图像),然后您可以在代码中使用:

Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png';

<img src={LogoImg}/>

精确,图像使用这种技术内联在 js 存档中.它可以用于小图像,但要明智地使用该技术.

a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.

这篇关于动态添加图片 React Webpack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆