废话很少话,来上车!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}); `;
整理不易,喜欢的话就顺手点个赞吧,您的赞会是咱们继续分享的动力 !