第二十三章:styled-components

是什么

  • 通過JavaScript改變CSS編寫方式的解決方案之一,從根本上解決常規(guī)CSS編寫的一些弊端。
  • all in js的思想

一、基本寫法

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

export default class App extends Component {
  render() {
    const StyledDiv = styled.div`
      background: red;
      width:100px;
      height:100px;
      span {        // 支持sass寫法
        color: #FFF;
      }
    `
    return (
      <StyledDiv>App
        <span>hhh</span>
      </StyledDiv>
    )
  }
}

二、props 穿透

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

export default class App extends Component {
  render() {
    const StyledDiv = styled.div`
      background: ${props => props.bg || `yellow`};
      width: 100px;
      height: 100px;
    `
    return (
      <div>
        <StyledDiv bg='blue'></StyledDiv>
      </div>
    )
  }
}

三、樣式化擴(kuò)展

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

export default class App extends Component {
  render() {
    const StyledButton = styled.button`
      border-radius: 5px;
      background: red;
      width: 100px; 
      height:36px;
      border: none;
    `
    const StyledButton2 = styled(StyledButton)`
      background: blue;
    `
    return (
      <div>
        <StyledButton>按鈕</StyledButton>
        <StyledButton2>按鈕</StyledButton2>
      </div>
    )
  }
}

四、 動畫

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

export default 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 (
      <StyledDiv>App</StyledDiv>
    )
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容