React Styled Component 的 CSS 方法优化

React Styled Component's CSS method optimization

哪个更优化,为什么?

我听说 Styled-component 的 css 方法非常昂贵,但我想知道多重嵌套 ${(prop) => {}} 是否比带有 css 的单个 fn 更昂贵里面使用的方法。

方法一

const Foo = styled.div`
  border-radius: 50%;
  display: flex;
  width: ${(props) => props.size};
  height: ${(props) => props.size};
  color: ${(props) => props.bgColor};
  background-color: ${(props) => props.bgColor};
`;

方法二

const Bar = styled.div`
  border-radius: 50%;
  display: flex;
  ${(props) => {
    return css`
      width: ${props.size};
      height: ${props.size};
      color: ${props.bgColor};
      background-color: ${props.bgColor};
    `;
  }}
`;

性能差异应该可以忽略不计。如果您的样式是静态的(没有插值),Styled Components 会做的唯一优化。

请注意 styled.div 或任何其他 Styled CSS 方法已经完成与 css 相同的工作。这些方法接受函数作为参数(而不是内插字符串)。所以你可以更进一步,这样做:

const Baz = styled.div((props) => css`
  border-radius: 50%;
  display: flex;
  width: ${props.size};
  height: ${props.size};
  color: ${props.bgColor};
  background-color: ${props.bgColor};
`);