英文:
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) =>
<div className={`bg-[url('${post.smallImage}')] md:bg-[url('${post.largeImage}')]`}
)}
This breaks with a very strange error:
Module not found: Can't resolve './${post.smallImage}'
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: '/pic1.png'
And if I don't use the variable it displays the image correctly:
{posts.map((post) =>
<div className={`bg-[url('/pic1.png')] md:bg-[url('pic2.png')]`}
)}
答案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't resolve './${post.smallImage}'
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 <img>
with srcset
attribute instead. Like this:
{posts.map((post, index) => (
<img key={index} src={post.smallImage} srcset={`${post.smallImage} 768px, ${post.largeImage}`} />
))}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论