首页 > 解决方案 > TypeError: Failed to construction 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function

问题描述

我有一个 data.js 文件,其中有:

export default [
{
    id: 1,
    title: "Black shirt Friday outfit",
    price: 30.99,
    image:URL("../images/black-shirt.jpg")
},
{
    id:2,
    title:"Look at me in brown boots",
    price:25.30,
    // image: (url("../images/brown-outfit.jpg"))
},
{
    id:3,
    title:"Cute winter",
    price: 21.90,
    // image: url("../images/cozy-outfit.jpg"),
},

我的问题是:我可以使用什么语法在我的 react-app 中渲染这些图像?

标签: reactjs

解决方案


您可以导入它们然后引用它们:

import Image1 from "../images/black-shirt.jpg"
import Image2 from "../images/brown-outfit.jpg"
import Image3 from "../images/cozy-outfit.jpg"

**export default [
{
    id: 1,
    title: "Black shirt Friday outfit",
    price: 30.99,
    image: Image1
},
{
    id:2,
    title:"Look at me in brown boots",
    price:25.30,
    image: Image2
},
{
    id:3,
    title:"Cute winter",
    price: 21.90,
    image: Image3
},**

然后,当您想在组件中使用它们时,您可以直接引用该导入的对象作为源:

data.map( item => 
   <img src={item.image} />
)

推荐阅读