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

25次阅读

共计 1165 个字符,预计需要花费 3 分钟才能阅读完成。

废话不多话,来上车!
安装:
npm install –save styled-components(或者 yarn add styled-components)
简述使用:
1、创建全局的样式:
首先创建一个 JS 文件,例如 style.js ①:import {createGlobalStyle} from ‘styled-components’ // 引全局包 ②:export const GlobalStyle = createGlobalStylemargin:0// “ 里面为项目需要的 css 内容 ③:在 react 组件内 把引入的 GlobalStyle 当做标签写入
class App extends Component {
render() {
return (<GlobalStyle></GlobalStyle>);
}
}

创建一个局部的样式
①: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});
`;

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

正文完
 0