美文网首页
css in js 的不归路(一)简单介绍

css in js 的不归路(一)简单介绍

作者: 万里凪 | 来源:发表于2019-02-25 16:42 被阅读0次

最开始在material-ui 里面看见了这种写法。
例如:

const styles = {
  root: {
    width: '100px',
    height: '100px',
    backgroundColor: 'red'
  },
};

class DemoDiv extends Component {
  render() {
    const { classes } = this.props;
    return (
        <div className={classes.root}></div>
    );
}

export default withStyles(styles)(DemoDiv);

widthStyles会创建一个高阶组件去传递props给DemoDiv。DemoDiv就可以获得对应的props中的样式。
因为本人比较菜鸟,所以不去讨论css in js究竟是好是坏。个人总体使用观感还算不错。
有兴趣可以看看Mark Dalgleish写的文章:
https://medium.com/seek-blog/a-unified-styling-language-d0c208de2660
列举了他认为JSS的种种好处。
对于民工选手来说,我只要知道它混合js变量写起来方便得多,同时有scope作用域,且编译时只用编译一次js,而不用再次编译其它预编译css语言就足够了。

尤其是使用styled-components,看到这样代码的情况下:

// Box.js
import styled from 'styled-components';
 
export const Box = styled.div`
  display: inline-block;
  background: pink;
  width: 200px;
  height: 200px;
  transition: transform 300ms ease-in-out;
`
 
export default Box;
// Trigger.js
import styled from 'styled-components';
 
import Box from './Box;'
 
export const Trigger = styled.div`
  width: 200px;
  height: 200px;
  border: 20px solid #999;
  background: #ddd;
 
  &:hover ${Box} {
    transform: translate(200px, 150px) rotate(20deg);
  }
`
 
export default Trigger;

顺便让我了解了一下标签函数。ES6鬼玩意还是挺多的。

const test = (arg1, arg2, arg3) => {
    console.log(arg1);  // ['分割', '分割', '分割']
    console.log(arg2);  // 123
    console.log(arg3);  // 234
}

test`分割${123}分割${234}分割`

不得不说,前端在反复折腾上面还是有天赋的。

styled-components能够摆脱css依赖,并且很快的一体式创建组件。
它将通过它标签函数创建出来的, 不带钩子函数的这种组件单独称为 组件(Component)
而将业务复杂的组件称为 容器(Container)
这样做的目的我认为是为了进一步将ui与业务分离。这样创建的ui组件基本上是与业务解耦的。

相关文章

网友评论

      本文标题:css in js 的不归路(一)简单介绍

      本文链接:https://www.haomeiwen.com/subject/gqygyqtx.html