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

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

问题描述

我一直在尝试找出如何通过React和Webpack动态添加图像.我在 src/images 下有一个图像文件夹,在 src/components/index 下有一个组件.我正在将url-loader与以下用于webpack的配置一起使用

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)} />

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

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,在此进行说明(

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天全站免登陆