安装style-components

    1. yarn add styled-components

    安装vscode-styled-components插件
    image.png
    引入

    1. import styled from 'styled-components'

    使用

    1. import 'antd/dist/antd.less'
    2. import styled from 'styled-components'
    3. function App() {
    4. const HomeWrapper=styled.div`
    5. font-size:50px;
    6. color:red;
    7. span{
    8. color:orange;
    9. &.active{
    10. color:green;
    11. }
    12. &:hover{
    13. color:blue;
    14. font-size:40px;
    15. }
    16. &::after{
    17. content:'ssss'
    18. }
    19. }
    20. `
    21. return (
    22. <div className="App">
    23. <h1 >我是一个标题</h1>
    24. <HomeWrapper>
    25. <h2>我是一个副标题</h2>
    26. <span>轮播1</span>
    27. <span className="active">轮播2</span>
    28. <span>轮播3</span>
    29. <span>轮播4</span>
    30. </HomeWrapper>
    31. </div>
    32. );
    33. }
    34. export default App;

    设置属性,可以通过attrs设置属性

    1. import 'antd/dist/antd.less'
    2. import styled from 'styled-components'
    3. function App() {
    4. const ChangeInput=styled.input.attrs({
    5. placeholder:'wangsu',
    6. bgColor:'red'
    7. })`
    8. background-color:#7a7ab4;
    9. color:${props=>props.bgColor}
    10. `
    11. return (
    12. <div className="App">
    13. <h1 >我是一个标题</h1>
    14. <ChangeInput type="text"/>
    15. </div>
    16. );
    17. }
    18. export default App;

    继承

    1. import React, { Component } from 'react'
    2. import styled from 'styled-components'
    3. const HYbutton=styled.button`
    4. color:red;
    5. border:1px solid #ccc;
    6. padding:10px 20px;
    7. `
    8. //这里使用继承
    9. const XLbutton=styled(HYbutton)`
    10. background-color:blue;
    11. `
    12. export default class Button extends Component {
    13. render() {
    14. return (
    15. <div>
    16. <HYbutton>这是一个按钮</HYbutton>
    17. <XLbutton>这是一个继承按钮</XLbutton>
    18. </div>
    19. )
    20. }
    21. }