styled-components

styled-components

它是通过JavaScript改变CSS编写方式的解决方案之一,从根本上解决常规CSS编写的一些弊端。

通过JavaScript来为CSS赋能,我们能达到常规CSS所不好处理的逻辑复杂、函数方法、复用、避免干扰。样式书写 将直接依附在JSX上面,HTMLCSSJS三者再次内聚。all in js的思想

npm i styled-components -S

1.透传props

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React, {Component} from 'react';
import styled from "styled-components";

class App extends Component {
render() {
const Styledinput = styled.input`
outline: none;
border-radius: 10px;
border-bottom: 1px solid blue;
`
const StyledDiv = styled.div`
background: ${props=>props.bg || 'yellow'};
width: 100px;
height: 100px;
`
return (
<div>
<Styledinput type="password" placeholder="输入" />


<StyledDiv bg="blue"></StyledDiv>
</div>
);
}
}

export default App;

2.样式化组件(一定要写className)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React, {Component} from 'react';
import styled from "styled-components";

class App extends Component {
render() {
const StyledChild = styled(Child)`
background: yellow;
`
return (
<div>
<StyledChild/>
</div>
);
}
}

function Child(props) {
return <div className={props.className}>
child
</div>
}

export default App;

3.样式扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React, {Component} from 'react';
import styled from "styled-components";

class App extends Component {
render() {
const StyledButton = styled.button`
width: 100px;
height: 100px;
background: yellow;
`
const StyledButton2 = styled(StyledButton)`
background: red;
`
return (
<div>
<StyledButton/>
<StyledButton2/>
</div>
);
}
}

export default App;

4.动画

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React, {Component} from 'react';
import styled,{keyframes} from "styled-components";

class App extends Component {
render() {
const myanimation = keyframes`
from{
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}

`
const StyledDiv = styled.div`
width: 100px;
height: 100px;
background: yellow;
animation: ${myanimation} 1s infinite;
`
return (
<div>
<StyledDiv/>
</div>
);
}
}

export default App;