首页 > 解决方案 > Styled-components - CSS 类不适用于 SSR

问题描述

当我使用链接导航到页面时遇到问题,我的 CSS 类并未全部应用。 在此处输入图像描述

而当我重新加载此页面时,所有类都已正确应用。 在此处输入图像描述

我认为这与使用带有样式的组件的服务器端渲染有关,但我不知道接下来要做什么来修复它。

样式化组件 v4.4.1

编辑:

窃听链接的代码(按钮组件)

import React from 'react'
import { Box, styled, css, th } from '@smooth-ui/core-sc'
import { darken, lighten, transparentize } from 'polished'
import theme from 'theme'
import Link from './Link'

const ButtonComponent = ({
  variant,
  size,
  children,
  condensed,
  isRow,
  maxWidth,
  ...props
}) => {
  const as = props.to ? Link : 'button'
  const type = as === 'button' ? props.type : null
  return (
    <Box {...props} type={type} as={as}>
      {children}
    </Box>
  )
}

const plainVariant = (bgColor, textColor) => css`
  background-color: ${th(bgColor)};
  color: ${th(textColor)};

  --focus-color: ${darken(0.08, theme[bgColor])};
  --active-color: ${lighten(0.16, theme[bgColor])};

  &:hover {
    color: ${th(textColor)};
    background-color: ${props => darken(0.08, props.theme[bgColor])};
  }

  &:focus {
    box-shadow: 0 0 0 2px ${props => transparentize(0.75, props.theme[bgColor])};
  }
`

const variants = {
  tertiary: plainVariant('orange', 'white'),
}

const Button = styled(ButtonComponent)`
  display: inline-flex;
  min-width: 200px;
  border-radius: 4px;
  border-width: 0;
  cursor: pointer;
  justify-content: center;
  align-items: center;
  text-align: center;
  text-decoration: none;
  user-select: none;
  outline-offset: 2px;
  vertical-align: middle;
  white-space: nowrap;
  font-weight: 500;
  padding: 0 16px;

  &:hover {
    text-decoration: none;
  }

  ${p => variants[p.variant]};
  ${p => sizes[p.size]};
  ${p =>
    /^gradient-*/.exec(p.variant) || p.rippled === false
      ? rippled.none
      : rippled.default};

  flex-direction: ${p => (p.isRow ? 'row' : 'column')};

  ${p =>
    p.condensed &&
    css`
      min-width: auto;
      line-height: 18px;
      padding: 15px;
    `};

  &:disabled {
    pointer-events: none;
    ${p => (disabled[p.variant] ? disabled[p.variant] : disabled.default)};
  }
`

export default Button

标签: cssreactjsstyled-componentsserver-side-rendering

解决方案


推荐阅读