白话速述 styled-components 4.x 的使用

废话不多话,来上车!

  1. 安装:

     npm install --save styled-components   (或者 yarn add styled-components)
  2. 简述使用:

    1、 创建全局的样式:
    
       首先创建一个JS文件,例如style.js
       ①:import { createGlobalStyle } from 'styled-components' // 引全局包
       ②:export const GlobalStyle = createGlobalStyle`margin:0`// ``里面为项目需要的css内容
       ③:在react组件内  把引入的 GlobalStyle 当做标签写入
       
         class App extends Component {
           render() {
               return ( <GlobalStyle></GlobalStyle> );
           }
         }
       
    2、创建一个局部的样式
    
      ①:import styled from 'styled-components';        //  引局部包
      ②:export const HeaderWrapper = styled.div``  //``里面为项目需要的css内容
      ③:③:在react组件内  把引入的 HeaderWrapper 当做标签写入
      
         class App extends Component {
           render() {
               return ( <HeaderWrapper></HeaderWrapper> );
           }
         }
      
    3、类嵌套:(类似于less sass用法大同小异)
    
    列举个项目实例:
    export const SearchWrapper = styled.div`
       position:relative;
       float:left;
       .iconfont{
           position:absolute;
       }
      `;
    
    
    4、增加属性写法:
       
        举例给A标签增加attrs属性
        export const Logo = styled.a.attrs({
             href:'/'
        })`
    
    
    
    
    5、 设置当前元素内指定的class类
          
           &.left{
               float:left;
           }
           &::placeholder{
               color:#999;
           }
    
    
    
    6、 styled-components 传值写法:
           样式内js文件用props去接收
           export const RecommendItem = styled.div`
               background: url(${(props) => props.imgUrl});
           `;
           
           react组件内给样式JS文件传入需要的地址
           <RecommendItem imgUrl="http://xxxxx"/>
    
    7、常见小坑:
    
       引图片不要直接写行内样式,默认会转化为字符串,导致加载图片失败,可用如下方式:
       import logoPic from '../../statics/logo.png';
       export const Logo = styled.a`
           background:url(${logoPic});
       `;
       
     
    

整理不易,喜欢的话就顺手点个赞吧,您的赞会是我们继续分享的动力 !

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章