reactjs - React Styled Components 生成过多的 css

标签 reactjs styled-components

举个例子:

import * as React from 'react';
import styled from 'styled-components';

const Ball = styled.div`
  width: 100px;
  height: 100px;
  border: 1px solid black;
  border-radius: 50%;
  background: radial-gradient(peachpuff 0% 8%, rgb(243, 169, 105) 10% 55%, rgb(192, 125, 66) 57% 100%) no-repeat;
  background-size: 150% 150%;
  background-position: center;
  background-position-x: 87%;
  background-position-y: 87%;
`;

const SmallBall = styled(Ball)`
  width: 50px;
  height: 50px;
`;

export default () => (
  <>
    <Ball name="Ball"></Ball>
    <SmallBall name="SmallBall"></SmallBall>
  </>
)

这是正在生成的标记: generated image showing hashed classes of each element

如果我要写出我希望生成的 CSS,它可能看起来像这样:

.sc-cHGsZl {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  border-radius: 50%;
  background: radial-gradient(peachpuff 0% 8%, rgb(243, 169, 105) 10% 55%, rgb(192, 125, 66) 57% 100%) no-repeat;
  background-size: 150% 150%;
  background-position: center;
  background-position-x: 87%;
  background-position-y: 87%;
}

.sc-cHGsZl.bmZbgS {
  width: 50px;
  height: 50px;
}

生成的是:

Generated styles for ball component

Generated styles for small ball component

如何让样式化组件输出更简洁的 CSS,其中公共(public)属性被分组并且没有不必要的重复?

最佳答案

您可以在 styled-component 中添加类名。

import * as React from 'react';
import styled from 'styled-components';

const Ball = styled.div.attrs({ className: "ball" })`
  width: 100px;
  height: 100px;
  border: 1px solid black;
  border-radius: 50%;
  background: radial-gradient(peachpuff 0% 8%, rgb(243, 169, 105) 10% 55%, rgb(192, 125, 66) 57% 100%) no-repeat;
  background-size: 150% 150%;
  background-position: center;
  background-position-x: 87%;
  background-position-y: 87%;
`;

const SmallBall = styled(Ball).attrs({ className: "small-ball" })`
  width: 50px;
  height: 50px;
`;

export default () => (
  <>
    <Ball name="Ball"></Ball>
    <SmallBall name="SmallBall"></SmallBall>
  </>
)

关于reactjs - React Styled Components 生成过多的 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57526358/

相关文章:

javascript - 从 facebook/react-native/Examples 运行示例时为 "Error watching file for changes: EMFILE"

javascript - 如何优化搜索算法

reactjs - React Hooks : Why is . useRef Hook 当前为 null?

javascript - 具有样式化组件的可重用参数化 CSS

javascript - 对样式化组件使用自定义文档时未传递 Prop

reactjs - 如何使用 Jest 和 Enzyme 在 React 中测试函数

javascript - 使用钩子(Hook)进行条件渲染

css - 样式组件也可以在服务器上呈现吗?

css - 有没有办法让文本粘在 div "border"上?

reactjs - ThemedStyledProps 类型上不存在属性 'name'