css - 使用 twin.macro 将外部样式应用于 Gatsby StaticImage
问题描述
我正在使用 gatsby-plugin-image 中的 StaticImage 和 twin.macro 进行 CSS 样式设置,并遵循本指南:https ://github.com/ben-rogerson/twin.examples/tree/master/gatsby-styled-components#getting -开始
...
import tw, { css, styled, theme } from 'twin.macro'
import { StaticImage } from 'gatsby-plugin-image'
...
<StaticImage
imgStyle={tw`rounded-lg shadow-2xl`}
style={tw`p-4`}
src="../images/image.jpeg"
width={300}
quality={95}
formats={['AUTO', 'WEBP', 'AVIF']}
alt="Description"
/>
使用“imgStyle”设置内部 img 元素的样式适用于 twin.macro。然而,对 StaticImage 的 style 属性应用相同的技术会导致以下错误:
不应在style={...}
道具中添加样式
如何将 twin.macro 应用于 StaticImage 的样式属性?
解决方案
图像在构建时加载和处理,因此对如何将 props 传递给组件有限制。这些值需要在构建时进行静态分析,这意味着您不能从组件外部将它们作为道具传递,或者使用函数调用的结果。您可以使用静态值,也可以在组件的本地范围内使用变量。
所以代码应该是这样的:
// Also OK
// A variable in the same file is fine.
const width = 300;
const height = 300;
const imgStyle= tw`rounded-lg shadow-2xl`;
export function Dino() {
// This works because the value can be statically-analyzed
const height = (width * 16) / 9
return <StaticImage
src="../images/image.jpeg"
width={width}
height={height}
style={imgStyle}
/>
}
推荐阅读
- linker - 在链接中,运行时地址和可重定位目标文件的 .text(机器代码)部分中的地址有什么区别?
- php - 如何在 Laravel 5 中保存用户限制?
- python - 在 tkinter 中将 Procedural 转换为 OO 的问题
- javascript - 关于画布动画和设备运动的问题
- java - 如何在文本视图的文本周围设置边框
- google-apps-script - 如何将链接附加到 Apps Script 上的形状或文本框?
- php - 如何使用php从数据库中显示当前登录用户的用户名
- sql - 按提供者汇总的支付总额的前 10 名,按状态分区 - PostgreSQL
- sql - 错误数量或类型的参数错误使用带参数的游标
- sql - 如何避免使用 SQL ORACLE 分组