举个例子:
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>
</>
)
如果我要写出我希望生成的 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;
}
生成的是:
和
如何让样式化组件输出更简洁的 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/