【问题标题】:Apply outer style to Gatsby StaticImage using twin.macro使用 twin.macro 将外部样式应用于 Gatsby StaticImage
【发布时间】:2021-04-05 21:52:27
【问题描述】:

我正在使用来自 gatsby-plugin-image 的 StaticImage 和 twin.macro 进行 CSS 样式设置,并遵循本指南:https://github.com/ben-rogerson/twin.examples/tree/master/gatsby-styled-components#getting-started

...
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 的样式属性?

【问题讨论】:

标签: css reactjs gatsby


【解决方案1】:

According to the Gatsby Image plugin docs:

图像是在构建时加载和处理的,所以有 对如何将 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}
  />
}

【讨论】:

  • 这并没有解释为什么它与 imgStyle 属性一起工作正常。它仅不适用于外部样式属性。
  • @NetUserHH 也许它可以工作,因为在构建时不需要进行静态分析,并且在渲染视图时将应用样式
  • @NetUserHH 你能试试我更新的答案吗?
  • 这有帮助!但是,请将您的答案更改为 style 属性,而不是 StaticImage 的 imgStyle。
猜你喜欢
  • 2021-06-13
  • 2021-12-09
  • 2021-09-20
  • 2021-06-20
  • 2021-02-22
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多