前期整了个我的博客系统,ui库也是变换了好几个,最后仍是用上了material-ui。发现该ui库时竟然没有像其余库同样引入css文件就能够显示,以为非常神奇(选他只是以为ui看的特别爽),后来才发现他样式是基于css in js的。css
发现material-ui的样式是基于css in js时,我非常想再换个ui库,毕竟用less、sass也是很不错的?何况,web发展这么久,好不容易把三大基本元素给拆分开了,如今又要合并起来,非常反感。不过,细细看了下,发现感受还不错。react
如其表面意思同样,便是在js中写css样式,先不谈这么写的好处与坏处。想一想咱们平时写css的难处:git
固然,这些问题在其余的像css module等方案中也是能够解决的。我的以为,最后一点用的非常不错,将css逐步能推向编程语言的范畴。github
material-ui中使用的是jss库,咱们尝试在react项目中使用他。react项目中要使用react-jss库,在create-react-app脚手架生成的代码中,修改App.js,web
import React, { Component } from 'react'; import withStyles from 'react-jss'; // 样式,使用colorBlue就对应后面的样式 const styles = { colorBlue: { color:'blue' } }; const Test = ({ classes }) => { return ( <span className={classes.colorBlue}>test</span> ); }; const StyledTest = withStyles(styles)(Test); class App extends Component { render() { return ( <div> <StyledTest></StyledTest> </div> ); } } export default App;
3000端口的页面能够看到字体已是蓝色的了,将全部的样式以样式名: 样式内容的方式写在styles对象之中,再用withStyles注入到组件之中(也可使用injectSheet代替withStyles),其实使用上去仍是不算太变扭。编程
看下在浏览器中渲染的class名,
命名颇有规律,更多其余规律能够本身尝试下。浏览器
那么在class方式定义的组件中怎么使用呢?忽略相同的import和styles的定义,看下组件的定义,sass
@withStyles(styles) class App extends Component { render() { const {classes} =this.props; return ( <span className={classes.colorBlue}>text</span> ); } } export default App;
不过很惋惜,在create-react-app项目中,es7的修饰器是不支持的,提示Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled。app
我也找了好多中处理方法,都仍是在报错,因此只能换种写法了,less
// @withStyles(styles) class App extends Component { render() { const {classes} =this.props; return ( <span className={classes.colorBlue}>text</span> ); } } export default withStyles(styles)(App);
这下页面正常了。更多的用法能够查看他的官方文档。
使用的时候又发现了个优势,
缺点确定也是有的,
理念了解后,能够尝试下其余的css in js库,好比styled-component等等。
留下项目地址:https://github.com/2fps/blooog 。
我的博客地址:http://www.zhuyuntao.cn/2019/...