從零到一 styled-components 4.x 的使用

廢話很少話,來上車!css

安裝:react

npm install --save styled-components   (或者 yarn add styled-components)

簡述使用:npm

一、 建立全局的樣式:sass

首先建立一個JS文件,例如style.js
①:import { createGlobalStyle } from 'styled-components' // 引全局包
②:export const GlobalStyle = createGlobalStylemargin:0// ``裏面爲項目須要的css內容
③:在react組件內 把引入的 GlobalStyle 當作標籤寫入app

class App extends Component {
        render() {
            return ( <GlobalStyle></GlobalStyle> );
        }
      }

建立一個局部的樣式less

①:import styled from 'styled-components'; // 引局部包
②:export const HeaderWrapper = styled.div //裏面爲項目須要的css內容
③:在react組件內 把引入的 HeaderWrapper 當作標籤寫入url

class App extends Component {
        render() {
            return ( <HeaderWrapper></HeaderWrapper> );
        }
      }

三、類嵌套:(相似於less sass用法大同小異)code

列舉個項目實例:component

export const SearchWrapper = styled.div`
    position:relative;
    float:left;
    .iconfont{
        position:absolute;
    }`;

四、增長屬性寫法:圖片

舉例給A標籤增長attrs屬性:
     
     export const Logo = styled.a.attrs({
          href:'/'
     })`

五、 設置當前元素內指定的class類

&.left{
            float:left;
        }
        &::placeholder{
            color:#999;
        }

六、 styled-components 傳值寫法:

樣式內js文件用props去接收
        
        export const RecommendItem = styled.div`
            background: url(${(props) => props.imgUrl});
        `;
        
        react組件內給樣式JS文件傳入須要的地址
        
        <RecommendItem imgUrl="http://xxxxx"/>

七、常見小坑:

引圖片不要直接寫行內樣式,默認會轉化爲字符串,致使加載圖片失敗,可用以下方式:
    
    import logoPic from '../../statics/logo.png';
    export const Logo = styled.a`
        background:url(${logoPic});
    `;

整理不易,喜歡的話就順手點個贊吧,您的贊會是咱們繼續分享的動力 !

相關文章
相關標籤/搜索