弱化css强化js网页html、css、js三要素在前端组件化过程中,如react、vue等组件框架的应用让html的弱化和js的强化成为一种趋势,而在这个过程中,其实还有一种趋势正在慢慢形成:css的弱化和js的强化。之前写过一篇关于CSS模块化的文章,但是对于js中css的概念并没有过多的解释,所以这次再深入一点。js中css的概念就是放弃原来的.css文件写样式,把样式写到js中,这样一个组件就可以对应一个文件,一个文件就是一个组件。1.支持的第三方库styled-components:仅reactradium:仅reactemotionaphroditepolishedjssglamorous:仅reactstyled-jsx:仅reactglamor:仅reactstyletron:仅react更多第三方库请参考css-in-js。2.写法js中css的写法一般有两种:使用es6模板字符串usingjsobjects{}2.1使用es6模板字符串styled-components、emotion、styled-jsx都采用这种写法。例如styled-components:importReactfrom'react';importstyledfrom'styled-components';//使用
标签创建一个React组件constTitle=styled.h1`font-size:1.5em;文本对齐:居中;color:palevioletred;`;//创建一个使用标签的React组件constWrapper=styled.section`padding:4em;background:papayawhip;`;//就像普通的React组件一样,只是它们都有自己的样式HelloWorld,这是我的第一个样式组件!对于例如,情感:从“情感”导入{css};constapp=document.getElementById('root');constmyStyle=css`color:rebeccapurple;`;app.classList.add(myStyle);这种写法的好处是,通过编辑器插件和lint插件(比如stylelint),像写普通的css一样,具有自动补全提示,错误提示,lint自动纠错等功能。2.2使用js对象{}radium,aphrodite,polished,jss,glamorous,glamour,styletron都是这样写的。比作镭:从“镭”导入镭;从“反应”导入反应;从“颜色”导入颜色;varstyles={base:{color:'#fff',':hover':{background:color('#0074d9').lighten(0.2).hexString()}},primary:{background:'#0074D9'},warning:{background:'#FF4136'}};classButtonextendsReact.Component{render(){返回({this.props.children});}}Button=Radium(Button);PrimaryWarning比如aphrodite:importReact,{Component}from'react';import{StyleSheet,css}from'aphrodite';conststyles=StyleSheet.create({red:{backgroundColor:'red'},blue:{backgroundColor:'blue'},hover:{':hover':{backgroundColor:'红色'}},small:{'@media(max-width:600px)':{backgroundColor:'red',}}});classAppextendsComponent{render(){return这是红色的。悬停时变为红色。当浏览器宽度小于600px时,它会变成红色。这是蓝色的。这是蓝色的,当浏览器宽度小于600px时变成红色。
;}}这种写法的好处是不需要es6的语法,对属性操作更方便3.决定是否使用如果你喜欢把样式和组件分开写,那么这个方法可能不适合你;如果你追求的是一个文件对应的组件,而文件就是一个组件,那就马上使用吧。4.更多后续博客,查看https://github.com/senntyou/blogs作者:沈育之(@senntyou)版权声明:免费转载-非商业-非衍生-保留署名(CreativeCommons3.0许可)