了解样式组件中的 css 辅助函数

12 css reactjs styled-components

样式化组件有一个CSS辅助函数。但我不明白什么时候应该使用它。

例如,这是他们使用它的示例:

import styled, { css } from 'styled-components'

const complexMixin = css`
  color: ${props => (props.whiteColor ? 'white' : 'black')};
`

const StyledComp = styled.div`
  /* This is an example of a nested interpolation */
  ${props => (props.complex ? complexMixin : 'color: blue;')};
`
Run Code Online (Sandbox Code Playgroud)

但是,如果我们从这里的文档中获取类似的示例,他们不会使用它:

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;
Run Code Online (Sandbox Code Playgroud)

他们的描述也不清楚,让我感到困惑:

一个辅助函数,用于通过插值从模板文字生成 CSS。如果由于标记模板文字在 JavaScript 中的工作方式而返回带有插值内函数的模板文字,则需要使用此选项。

有人可以帮助解释为什么我们需要它吗?

PS这个答案也不使用它

小智 2

当我为组件创建变体时,我使用 css 函数:

那是变体切换器:

const sizeVariant: Record<NonNullable<StyledLogoProps['size']>, ReturnType<typeof css>> = {
  small: css`
    width: 44px;
    height: 44px;
  `,
  regular: css`
    width: 93px;
    height: 93px;
  `,
};
Run Code Online (Sandbox Code Playgroud)

该组件是由“styled-components”创建的:

interface StyledLogoProps {
  size: 'small' | 'regular';
}

export const StyledLogo = styled.div<StyledLogoProps>`
  ${({ size }) => sizeVariant[size]}
`;
Run Code Online (Sandbox Code Playgroud)

这是在反应中的用法:

<>
  <StyledLogo size="regular" />
  <StyledLogo size="small" />
</>
Run Code Online (Sandbox Code Playgroud)

相当有用的东西