安装 : npm install tyled-components

基本用法

  1. import styled from 'styled-components'
  2. //变成有样式的组件
  3. const StyleApp = styled.div`
  4. background:yellow;
  5. border:1px solid black;
  6. ul{
  7. li{
  8. color:red;
  9. }
  10. }
  11. &:hover{
  12. background:pink
  13. }
  14. `
  15. /*
  16. <StyleApp>
  17. <ul>
  18. <li>1111</li>
  19. <li>22222</li>
  20. </ul>
  21. </StyleApp>
  22. */

透析props

样式动态化(由props决定)

import React, { Component } from 'react'
import styled from 'styled-components'

export default class App extends Component {


    render() {
        const StyledInput = styled.input`
         outline:none;
         border-radius:10px;
         border-bottom:1px solid red;
        `

        const StyledDiv = styled.div`
          background:${props=>props.bg || 'yellow'};
          width:100px;
          height:100px;
        `
        return (
            <div>
                App
                <StyledInput type="password" placeholder="输入"/>

                <StyledDiv bg="red"></StyledDiv>
            </div>
        )
    }
}

样式化组件

将样式作为子节点props传入

import React, { Component } from 'react'
import styled from 'styled-components'

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

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

样式拓展(继承)

继承另一个组件样式 并拓展自身样式

import React, { Component } from 'react'
import styled from 'styled-components'

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

动画

import React, { Component } from 'react'
import styled,{keyframes} from 'styled-components'
export default class App extends Component {
    render() {
        const myaniamtion = keyframes`
         from{
             transform:rotate(0deg)
         }
         to{
            transform:rotate(360deg)
        }
        `
        const StyledDiv = styled.div`
         width:100px;
         height:100px;
         background:yellow;
         animation: ${myaniamtion} 1s infinite;
        `
        return (
            <div>
                <StyledDiv/>
            </div>
        )
    }
}