简体   繁体   English

Next.js - 动态图像

[英]Next.js - dynamic images

I'm working with next.js and trying to get images dynamically like this:我正在使用 next.js 并尝试像这样动态获取图像:

{list.map((prod) => (
      <div className={styles.singleProduct}>
          <h6>{prod.Brand.toUpperCase()}</h6>
          <p>{prod.ProductName}</p>
          <img
              src={require(`../public/assets/products/${prod.ProductName
              .replace(" ", "-")}.png`)}
           /> 
       </div>
  ))}
   

With this code I get the following error: "./public/assets/products/Product-One.png 1:0 Module parse failed: Unexpected character '�' (1:0)"使用此代码,我收到以下错误:“./public/assets/products/Product-One.png 1:0 Module parse failed: Unexpected character '�' (1:0)”

When I hard code the image everything works, f.ex.:当我对图像进行硬编码时,一切正常,例如:

... 
<img
    src={require(`../public/assets/products/Product-One.png`)}
/> 
...

So I suppose that I get the error because of the dynamic variable??所以我想我因为动态变量而得到错误? Could someone help me with the issue?有人可以帮我解决这个问题吗? Thanks a lot!非常感谢!

I was getting the same error for svg images so I use this package https://www.npmjs.com/package/react-inlinesvg .对于 svg 图像,我遇到了同样的错误,所以我使用这个 package https://www.npmjs.com/package/react-inlinesvg What this package does under the hood, it loads the image url during runtime as a data uri and then convert it to image format (in this case it does svg).这个 package 在幕后做了什么,它在运行时将图像 url 作为数据 uri 加载,然后将其转换为图像格式(在这种情况下它是 svg)。 After converting the image it uses the image as a react component and insert it as child.转换图像后,它将图像用作反应组件并将其作为子组件插入。

So, with the help here especially from Alvaro I finally have the solution.所以,在阿尔瓦罗的帮助下,我终于有了解决方案。 The following code works:以下代码有效:

src={`/assets/products/${prod.ProductName.replace(/ /g, "-")}.png`} 

or或者

src={"/assets/products/" + prod.ProductName.replace(/ /g, "-") + ".png"} 

It seems as "require" doesn't work well with variables.似乎“要求”不适用于变量。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM