要求src映像的路径为变量 [英] Require path for src image as variable

查看:126
本文介绍了要求src映像的路径为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用create-react-app创建一个react项目。

I'm working on a react project created with the create-react-app.

我有一组数据对象。对象中的属性之一是图像路径。如果我将路径直接放在src标记中并使用require,那么它会起作用。

I've got an array of data objects. One of the properties in the object is an image path. If I put the path directly in the src tag and use require it works.

<img src={require(`./../../../assets/images/1425629.svg`)} />

如果我使用变量,则需要做的事情是因为路径来自对象,出现以下错误:

If I'm using a variable, what I need to do because the path is coming from the object, I'm getting the following error:

<img src={require(`${data.image}`)} />

错误:找不到模块'./../../。 ./assets/images/1425629.svg'

[更多代码编辑]

这是我的对象的基础(此处的复杂程度有所降低)

This is the basis of my object (made it less complex for here)

const data = [
    {
        image: `./../../../assets/icons/1458.svg`,
        title: 'title1',
        description: 'description1'
    },
    {
        image: `./../../../assets/icons/48754.svg`,
        title: 'title2',
        description: 'description2'
    },
    {
        image: `./../../../assets/icons/7548.svg`,
        title: 'title3',
        description: 'description3'
    }
];

此容器组件将正确的数据传递给功能组件

This container component is passing the right data to a functional component

const BlogInfo = ({ id }) => <Info {...data[id]} />;

这是功能组件的基础

const Info = ({ image, title, description }) => {
    return (
        <div>
            <img src={require(`${image}`)} />
            <h1>{title}</h1>
            <p>{description}</p>
        </div>
    );
};

因此在功能组件中,以下工作正常

So in the functional component, the following is working

<img src={require(`./../../../assets/images/1425629.svg`)} />

import icon from './../../../assets/images/1425629.svg';

<img src={icon} />

但是我想要(动态地)实现这一目标的方法不是

but the way I want to achieve this (dynamically) isn't

<img src={require(`${image}`)} />


推荐答案

错误是因为托管了React应用时图像路径将更改为相对于主机路径的动态值。这是由于webpack捆绑造成的。因此,react使用来自webpack的require.context。

The error is because when the react app is hosted then the image path changes to a dynamic value which is relative to the path of your host. This is due to bundling by webpack. So react uses require.context which comes from webpack.

导出json并获取所有必需的路径。然后执行以下操作

export json and get all your required paths. Then do as follows

var cache = [];

function importAll (r) {
  r.keys().forEach((key,index) => cache[index] = r(key));
}    

//path from json
importAll(require.context(path, false, /\.(png|jpe?g|svg)$/));
export default cache;

缓存将是您需要的所有图像的数组

cache will be an array of all the images you need

在您的img标签中执行以下操作

in your img tag do as follows

<img src={cache[0]}/>

如果您已经知道路径,则可以将其导入为

if you already know the path you could just import it as

import img from imgPath
...
<img src = {img}/ >

希望这会有所帮助

这篇关于要求src映像的路径为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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