什么是style-components?
style-components是针对React写的一套css in js框架,简单来讲就是在js中写css。相对于与预处理器(sass、less)的好处是,css in js使用的是js语法,不用重新再学习新技术,也不会多一道编译步骤,无疑会加快网页速度。
作者:恰到半生
链接:https://www.jianshu.com/p/27788be90605
来源:简书
剩下的官网自己看https://styled-components.com
问题的出现
在使用了style-components
框架之后,所有的样式都被封装为一个个组件,在进行渲染的同时就能使用自定义的样式。
但问题来了!!!
-
react项目不会再识别
.css
文件(也可能我没有发现两者同时使用的方法) -
正常使用webpack打包的React项目,在项目打包成bundle的时候会对代码丑化(uglyfy),因此组件的类名会在打包时被混淆,这也使得添加类名变得繁琐。
如何解?
划重点:
把待使用的css文件转换为使用style-components
框架的.js
文件,然后引入即可。
看个例子——animate的使用
animate
其实是封装好的CSS动画,在平时使用时只需要:
下载 — 引入 — 在需要添加动画的标签上添加类名animated xxx
(不详细讨论,自己上GitHub看https://github.com/daneden/animate.css)
接下来我们在React项目中,把它变成一个模块来使用
1.animate.css源码长这样
@charset "UTF-8";
/*!
* animate.css -https://daneden.github.io/animate.css/
* Version - 3.7.2
* Licensed under the MIT license - http://opensource.org/licenses/MIT
*
* Copyright (c) 2019 Daniel Eden
*/
@-webkit-keyframes bounce {
from,
20%,
53%,
80%,
to {
-webkit-animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
40%,
43% {
-webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
-webkit-transform: translate3d(0, -30px, 0);
transform: translate3d(0, -30px, 0);
}
70% {
-webkit-animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
animation-timing-function: cubic-bezier(0.755, 0.05, 0.855, 0.06);
-webkit-transform: translate3d(0, -15px, 0);
transform: translate3d(0, -15px, 0);
}
90% {
-webkit-transform: translate3d(0, -4px, 0);
transform: translate3d(0, -4px, 0);
}
}
===>>>...略
2.封装
把.css
文件改为.js
文件,代码改成这样:
import {createGlobalStyle} from 'styled-components'; //用于生成处理全局样式
export const Animate=createGlobalStyle`
原animate.css文件的源码粘贴过来
`;
由于animate需要用于全局动画,所以我用styled-components
模块中的createGlobalStyle
方法将其封装为全局样式。
3.在主文件中使用
中国人都知道入口文件是App.js
在里面引用吧:
import ... // 其它必要引用
import {Animate} from "./static/animate";
function App() {
return (
<Fragment>
<Animate/>
{/*其它组件*/}
</Fragment>
)
4.肆无忌惮添加类名
比如某个子组件文件index.js
的render
函数:
render() {
return(
<ServiceWrapper>
<div className={'animated bounceInUp'}>
<InfoSource />
</div>
</ServiceWrapper>
)
}
当然,如果你想在某个组件上添加额外的类名,比如InfoSource
上你想用别的类来定义样式,仿照刚刚的方法,把css
文件封装成.js
文件,在这个index.js
文件中引入刚刚封装的组件,在render
函数里使用这个组件,完事儿了!