廢話不多話,來上車!
-
安裝:
npm install --save styled-components (或者 yarn add styled-components)
-
簡述使用:
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}); `;
整理不易,喜歡的話就順手點個贊吧,您的贊會是我們繼續分享的動力 !