首页 > 解决方案 > 使用 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 的样式属性?

标签: cssreactjsgatsby

解决方案


根据 Gatsby Image 插件文档:

图像在构建时加载和处理,因此对如何将 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}
  />
}

推荐阅读