简体   繁体   English

图像路径在 React 中不起作用,因为我尝试在 object 中使用图像路径,它也在数组内部

[英]Image path not working in React as I tried to use use Image path inside an object which is also inside of an array

I wanted to use image path inside an object as a value.我想使用 object 中的图像路径作为值。 This object is also inside of an array.这个 object 也在一个数组里面。 But the image is not showing up.但是图像没有显示出来。 Can anyone explain why?谁能解释为什么? My code:我的代码:

const Data =[
    {
        imgsrc:"{require('../src/img/2.jpg')}",
        title:'this is me',
        sname:'Dark',
        link:'https://www.google.com'
    },
    {
        imgsrc:"{require('../src/img/1.jpg')}",
        title:'this is me',
        sname:'Dark',
        link:'https://www.google.com'
    }
];

export default Data;

Because this are strings, not proper import statements?因为这是字符串,而不是正确的导入语句? Webpack or whatever tool you are using is unable to find this imports and interpret them correctly. Webpack 或您使用的任何工具都无法找到此导入并正确解释它们。

Try something like this:尝试这样的事情:

const image1 = require('../src/img/1.jpg')
const image2 = require('../src/img/1.jpg')
const Data =[
    {
        imgsrc:image1,
            title:'this is me',
            sname:'Dark',
            link:'https://www.google.com'
    },
    {
        imgsrc:image2,
            title:'this is me',
            sname:'Dark',
            link:'https://www.google.com'
    }`enter code here`
];

You cannot use require in the way you are proposing.您不能以您提议的方式使用 require 。 Well, actually of course there is a way someone know how it can work, but I would highly recommend to not do it.好吧,实际上当然有人知道它是如何工作的,但我强烈建议不要这样做。

Consider this option:考虑这个选项:

const image2 = require('../src/img/2.jpg');

const Data =[
    {
        imgsrc:image2,
        title:'this is me',
        sname:'Dark',
        link:'https://www.google.com'
    },
];

export default Data;

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

相关问题 在CSS类中使用Javascript图像路径 - Use Javascript image path inside css class 我如何将 object 推入 object 内的数组,该数组也在另一个数组内 - How do i push an object into an array which is inside an object which is also inside an another array 使用.map() 在 object React 中迭代数组 - Use .map() to iterate array inside a object React 如何在不导入或不需要的情况下使用 React Typescript 中路径中的图像? - How to use an image from a path in React Typescript without import or require? 如何使用 static 图像路径在 React JS 中作为道具传递 - How to use the static image Path passed as props in React JS cakephp-js文件中图像的路径 - cakephp - path for image inside js file Vue 3 - 图像相对路径语法(内部方法) - Vue 3 - Image relative path syntax (inside method) 尝试使用 react-image-gallery 时出现“无法加载图像”错误,即使文件路径绝对正确 - Trying to use react-image-gallery and I get “could not load the image” error even though the file path is definitely correct 图像路径在反应组件 laravel 项目中不起作用 - Image path is not working in react components laravel project 为什么我的图像路径不起作用? - Why is my path to my image not working in react?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM