Reactjs要求变量中的图像url不起作用

问题描述 投票:2回答:2

奇怪的问题

我动态地在源目录中包含图像的路径。

将图像目录作为字符串放入工作正常(我注释掉的部分),但是只要我把它放在一个变量中就会给出错误“找不到模块”。“”

   var imageDir="assets/img/MyImage.png";
  --Working     // const imageData= require('assets/img/MyImage.png');
  --Not Working    const imageData= require(imageDir);

谁知道为什么?

同样的问题Here不幸的是没有答案

node.js file require
2个回答
1
投票

Webpack需要知道在编译时要捆绑哪些文件,但表达式只在运行时给出值,需要require.context

/* If structure like:

    src -
         |
          -- index.js (where these code deploy)
         |
          -- assets - 
                     |
                      --img
*/  


let assetsPath = require.context('./assets/img', false, /\.(png|jpe?g|svg)$/); 

// See where is the image after bundling.
// console.log(assetsPath('./MyImage.png'));
// In fact you could put all the images you want in './assets/img', and access it by index: './otherImg.jpg' 
var newelement = {
    "id": doc.id,
    "background": assetsPath('./MyImage.png');
};

0
投票

如果您希望在您的反应Web应用程序上使用图像,您可以使用下一个代码

当直接在html标签中使用时,但是如果你可以在java脚本的一部分中使用,你必须使用const image = require('../Assets/image/03.jpg')并在这个{image}之间调用这个常量

© www.soinside.com 2019 - 2024. All rights reserved.