同一组件中的不同样式,仅在 gatsby 构建版本中

Posted

技术标签:

【中文标题】同一组件中的不同样式,仅在 gatsby 构建版本中【英文标题】:Different styles in same component, only in gatsby build version 【发布时间】:2021-02-10 21:32:01 【问题描述】:

我的 gatsby 网站的每个页面都有相同的导航组件。在开发模式下,每种样式都可以正常工作。每个页面上的开发模式按钮:

但在主页(“/”)上 only 的 gatsby 的生产版本中,它看起来像这样:

在生产模式下,除了主页,在每个页面上它都像在开发中一样工作,主页上的样式不仅适用于这个按钮。我也不知道为什么。

这是导航组件的样子:

const NavigationSearchBar = () => 
  const  isMobile, windowWidth  = useResize()
  const  setSearch  = useNavigationSearchBar()
  return (
    <StyledContainer>
      <Row>
        !isMobile && (
          <Col md="2">
            <NavbarBrand href="/">
              <img src='/images/logo.svg' />
            </NavbarBrand>
          </Col>
        )
        <StyledSearchBar sm="12" md= size: 6, offset: 2 >
          <StyledForm>
            <SearchInput
              type="text"
              name="search"
              onChange=e => setSearch(e.target.value)
            />
            <SimpleButton  background="primary" color="whiteColor">
              Search
            </SimpleButton>
          </StyledForm>
        </StyledSearchBar>
        <StyledCol2 sm="12" lg="2">
          <SimpleButton
            width=windowWidth >= 400 ? '160px' : '100%'
            background="primaryOrange"
            color="blackColor"
          >
            On Sale
          </SimpleButton>
        </StyledCol2>
      </Row>
    </StyledContainer>
  )


export default NavigationSearchBar

没什么特别的,这里没有业务逻辑。这是该按钮在样式化组件中的样式:

const SimpleButton = styled.button`
  width: $( width ) => width;
  background: $( background ) =>
    theme.colors[background] ? theme.colors[background] : background;
  padding: $( padding ) => (padding ? padding : '0.5rem 0');
  text-align: center;
  border: 1px solid
    $( background ) =>
      theme.colors[background] ? theme.colors[background] : background;
  border-radius: 8px;
  text-transform: uppercase;
  color: $( color ) => (theme.colors[color] ? theme.colors[color] : color);
  letter-spacing: 1.5%;
  font-weight: $theme.fontWeights.medium;
  position: relative;
  z-index: 1;
`

我认为 gatsby 构建过程可能存在一些问题,因为在生产模式中除了这个按钮之外的所有东西都与开发模式中的样式相同。

你知道它为什么不工作吗?

我刚刚注意到刷新时没有样式,但如果我通过应用程序中的 gatsby 链接进入页面,则应用样式。例如,如果我在页面 /login 上应用了所有样式,但是当我通过单击 F5 刷新时,gatsby 输入 /login/ 并且所有样式都消失了(这仅在生产模式下发生)。

【问题讨论】:

【参考方案1】:

我忘记为 gatsby 安装 styled-components 插件。 在开发时一切正常,但在构建版本问题开始。

待办事项:

npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components

别忘了在 gatsby-config.js 文件中添加插件:

module.exports = 
  /* Your site config here */
  plugins: [
    ....other plugins
    'gatsby-plugin-styled-components',
  ],


【讨论】:

以上是关于同一组件中的不同样式,仅在 gatsby 构建版本中的主要内容,如果未能解决你的问题,请参考以下文章

Gatsby 构建/s-s-r 换出导致显示错误的组件

将自定义类/样式传递给 Gatsby (React) 中的样式化组件

用于样式化组件和 Gatsby / Safari 支持的 Gap Polyfill

使用带有样式组件的 Material-UI 主题

React / Gatsby - 根据屏幕大小渲染不同的组件

Gatsby Styled Components , CSS 显示在 <head>