样式复用
/*
不同元素样式复用:as属性
*/
const TextHightlight = styled.span`
font-weight: 500;
`;
<TextHightlight as="div">DivTextHightlight</TextHightlight>;
/*
同元素样式的复用和拓展:继承
*/
const TextHightlightError = styled(TextHightlight)`
color: red;
`;
继承
styled(Button)
继承后可以编辑
const Button = styled.button`
color: #bf4f74;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid #bf4f74;
border-radius: 3px;
`;
// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`;
styled.xxx 一般适用于简单原生标签
styled(xxx)一般适用于自定义 react 组件
as 动态更改标签
Button -> a 标签
const Button = styled.button``
<Button as=“a" href="#">
常用于导航栏按钮和链接间的条件切换
组件也可以切换成自定义组件
// xxx组件,但是拥有Button组件的样式
<Button as={xxx}>
公共属性
传参为属性对象,用于传递静态属性
/*
属性传递attrs
*/
const VolcaBlank = styled.a.attrs({
target: "_blank",
rel: "noopener noreferrer",
})`
color: #1664ff;
:visited {
color: #1664ff;
}
:hover {
color: #4086ff;
}
`;
传参为函数,用于传递计算属性
//styled-components运行该函数时为其传入props参数(TextWithPopover使用时传入的props)
const TextWithPopover =
styled(Typography.Text).attrs(({ style, ellipsis }) => ({
style: {
width: "170px",
margin: 0,
...style,
},
ellipsis: {
showTooltip: { type: "popover" },
...(typeof ellipsis === "object" ? ellipsis : {}),
},
})) <
{ style: any } >
`
font-size: 12;
`;