1.安装依赖
yarn add styled-components
2.安装 ts 声明文件
yarn add --dev @types/styled-components
3.注入组件
// Button.tsx组件
import styled from 'styled-components'
const Button = styled.button`
color : red;
border : none;
background : green;
&:hover{
background : black;
}
`
export default Button;
// *.tsx
import Button from './Button'
<Button>自定义的按钮</Button>
4.动画
const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`
const Rotate = styled.div`
display: inline-block;
animation: ${rotate} 2s linear infinite;
padding: 2rem 1rem;
font-size: 1.2rem;
`
render(<Rotate>加载中图片</Rotate>)
5.props动态样式和通过.attr附加props
// props动态样式
const ScButton = styled.button `
background: ${props => props.primary ? "blue" : "white"};
color: ${props => props.primary ? "white" : "blue"};
border: 2px solid palevioletred;
border-radius: 3px;
padding: 0.25em 1em;
`
export default () => {
return (
<div>
<Button>Normal</Button>
<Button primary>Primary</Button> {/* 通过 props 实现动态样式 */}
</div>
)
// .attrs允许附加静态或动态的 props
const Input = styled.input.attrs((props) => ({
type: "password", // 定义静态的 prop
size: props.size || "1em", // 定义动态的 prop
}))`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* 最终的 props 是合并 attrs 返回值的 props 的结果 */
margin: ${(props) => props.size};
padding: ${(props) => props.size};
`
render(
<div>
<Input placeholder="A small text input" />
<Input placeholder="A bigger text input" size="2em" />
</div>
)
5.样式继承
const ScButton = styled.button`
color: white;
background-color: blue;
border: 2px solid palevioletred;
border-radius: 3px;
padding: 0.25em 1em;
`
// 继承
const ScExtendedButton = styled(ScButton)`
color: blue;
background-color: white;
margin-top: 1em;
`
6.样式化第三方组件
import { Button } from '@alifd/next'
const ScButton = styled(Button)`
margin-top: 12px;
color: green;
`
render( <div> <ScButton>Styled Fusion Button</ScButton> </div> )
7.mixin
import styled, { css } from 'styled-components';
import { Button as FusionButton } from '@alifd/next';
const mixinCommonCSS = css`
margin-top: 12px;
border: 1px solid grey;
borde-radius: 4px;
`
const ScButton = styled.button`
${mixinCommonCSS}
color: yellow;
`
const ScFusionButton = styled(FusionButton)`
${mixinCommonCSS}
color: blue;
`;