gpt4 book ai didi

reactjs - React Styled Components 生成过多的 css

转载 作者:行者123 更新时间:2023-12-05 07:20:21 24 4
gpt4 key购买 nike

举个例子:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com