如何在将数组映射到组件时为不同尺寸指定背景图像?

huangapple go评论75阅读模式
英文:

How to specify a background image for different sizes when mapping an array to component?

问题

如何使用变量在不同尺寸下显示背景图像?

{posts.map((post) =>
  <div className={`bg-[url('${post.smallImage}')] md:bg-[url('${post.largeImage}')]`}
)}

这会导致一个非常奇怪的错误:

找不到模块:无法解析'./${post.smallImage}'
    
https://nextjs.org/docs/messages/module-not-found
    
导入所请求模块的跟踪:
./src/app/globals.css

如果我记录post.smallImage,它会正确记录图像路径:'/pic1.png'
如果我不使用变量,它会正确显示图像:

{posts.map((post) =>
  <div className={`bg-[url('/pic1.png')] md:bg-[url('/pic2.png')]`}
)}
英文:

How to show a background image for different sizes using a variable?

{posts.map((post) =&gt;
  &lt;div className={`bg-[url(&#39;${post.smallImage}&#39;)] md:bg-[url(&#39;${post.largeImage}&#39;)]`}
)}

This breaks with a very strange error:

Module not found: Can&#39;t resolve &#39;./${post.smallImage}&#39;

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./src/app/globals.css

If I log post.smallImage it logs the image path correctly: &#39;/pic1.png&#39;
And if I don't use the variable it displays the image correctly:

{posts.map((post) =&gt;
  &lt;div className={`bg-[url(&#39;/pic1.png&#39;)] md:bg-[url(&#39;pic2.png&#39;)]`}
)}

答案1

得分: 1

以下是翻译好的部分:

以下错误

Module not found: Can't resolve './${post.smallImage}'

来自于 webpack,因为它尝试解析 url() 内部的路径并将其作为资源导入。

Tailwind 文档 建议避免使用 JavaScript 生成 Tailwind 类。代码必须能够静态分析,或者是“可净化的”:

避免在模板中使用字符串拼接动态创建类字符串,否则 PurgeCSS 将不知道保留这些类。

在这种情况下,看起来更有效的方法是使用带有 srcset 属性的 <img>。像这样:

{posts.map((post, index) => (
  <img key={index} src={post.smallImage} srcset={`${post.smallImage} 768px, ${post.largeImage}`} />
))}
英文:

The following error

Module not found: Can&#39;t resolve &#39;./${post.smallImage}&#39;

comes from webpack, because it tries to resolve path to whatever is inside url() and import it as an asset.

Tailwind docs recommend to avoid generating Tailwind classes with JavaScript. Code must be statically analyzable, or "purgeable":

> it is important to avoid dynamically creating class strings in your
> templates with string concatenation, otherwise PurgeCSS won’t know to
> preserve those classes.

In this situation, looks like it would be more efficient to use &lt;img&gt; with srcset attribute instead. Like this:

{posts.map((post, index) =&gt; (
  &lt;img key={index} src={post.smallImage} srcset={`${post.smallImage} 768px, ${post.largeImage}`} /&gt;
))}

huangapple
  • 本文由 发表于 2023年7月27日 19:37:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定