【问题标题】:TypeError: Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a functionTypeError: Failed to construction 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function
【发布时间】:2020-10-19 23:05:57
【问题描述】:

我有一个 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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
          const data = [
            {
              id: 1,
              title: "Black shirt Friday outfit",
              price: 30.99,
              image:"../images/black-shirt.jpg"
          },
          {
              id:2,
              title:"Look at me in brown boots",
              price:25.30,
              image: "../images/black-shirt.jpg"
          },
          {
              id:3,
              title:"Cute winter",
              price: 21.90,
             image: "../images/black-shirt.jpg"
          }
          ];
      
      export default data;
      

      在您的主文件中:

      return {
      <div>
         <ul>
              {data.map(item =><img key={Math.random()} src={require(`../images/${item.image}.jpg`)} /> 
          </ul>
      </div>
      ;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-09-29
        • 2021-02-21
        • 1970-01-01
        • 2022-12-27
        • 1970-01-01
        • 2017-11-16
        • 2021-03-24
        • 2022-11-09
        • 1970-01-01
        相关资源
        最近更新 更多