【问题标题】:Loading image location from JSON file dynamically - (Cannot find module...) React, Next.js从 JSON 文件动态加载图像位置 - (找不到模块...) React, Next.js
【发布时间】:2021-03-29 10:53:28
【问题描述】:

我正在尝试从这个 JSON 文件动态加载信息并将其插入到组件中。

{
    "team": [
        {
            "id": "",
            "name": "",
            "role": "",
            "bio": "",
            "major": "",
            "image": "akh.jpg"
        },
       {
            "id": "",
            "name": "",
            "role": "",
            "bio": "",
            "major": "",
            "image": "chr.jpg"
        }
    ]
}

我的代码位置是/pages/about/index.js,我的JSON文件是/pages/about/about.json

我解析代码的方式是这样的:

var data = require('./about.json')
var teams = data['team'];

<ul>
   {teams.map((person) => {
      var basePath = "/public/images/profiles/";
      var loc = require(basePath + person.image);
      return <ProfileCard key={person.id} id={person.id} name={person.name} role={person.role} major={person.major} image={loc} />
   })}
</ul>

组件位于同一个文件中。我只附加配置文件中的 img 元素,因为其余的工作正常。

<img className="" src={require(props.image)}></img>

如果我取出 img 元素或放入实际路径,它可以完美运行,但这种方式不起作用。我能找到的唯一类似的帖子是这个,但它从未得到答案。 StackOverflow: importing image dynamically (React Js) (Require img path cannot find module)

更新代码 1:

<ul>
  {teams.map((person) => {
    var basePath = "/public/images/profiles/";
    return <ProfileCard 
       key={person.id} 
       id={person.id} 
       name={person.name} r
       role={person.role} 
       major={person.major} 
       image={`${basePath}/${person.image}`} />
   })}
</ul>

而组件去掉require()之后就是这个样子了。

<img src={props.image}></img>

更新的代码 2: 从 img 切换到 next/image 并且可以正常工作!我不得不删除最后一个 / 并且它起作用了。

【问题讨论】:

    标签: javascript json reactjs next.js nextjs-image


    【解决方案1】:

    在 NextJS 中,图像由 /(根)提供,因此您不必在路径中使用 public,或者为此使用 require。只需生成一个标准字符串。它应该很简单......

    import aboutJson from './about.json'
    
    const teams = aboutJson[teams]
    
    const basePath = '/images/profiles/'
    
    const Teams = () => (
       <ul>
          {teams.map((person) => <ProfileCard 
             key={person.id} 
             id={person.id} 
             name={person.name} 
             role={person.role} 
             major={person.major} 
             image={`${basePath}/${person.image}`} 
           />
       )}
       </ul>
    )
    
    const ProfileCard = ({ image, ...props }) => <img src={image} />
    

    另外,next 确实提供了自己的图片组件:

    import Image from 'next/image'
    
    const ProfileCard = ({ image, ...props }) => <Image src={image} />
    

    【讨论】:

    • 这可能是潜在问题的迹象,因为当我删除要求时,图像根本不会加载。我得到“找不到图像”方形符号。
    • 你能发布你更新的代码吗?另外,我更新了我的示例以删除 public
    • 也更新了 next/image 组件。
    • 删除了 /public 和 require() 并更新了帖子。还是不行。还没有尝试过 next/image 组件,但看起来很有希望。
    • 在我删除了 basePath 末尾的额外 / 后它起作用了。谢谢!
    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2021-11-22
    • 2019-02-09
    • 2021-07-23
    相关资源
    最近更新 更多