Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

我为什么使用styled-components #15

Open
GeoffZhu opened this issue Feb 11, 2019 · 0 comments
Open

我为什么使用styled-components #15

GeoffZhu opened this issue Feb 11, 2019 · 0 comments

Comments

@GeoffZhu
Copy link
Owner

GeoffZhu commented Feb 11, 2019

看了不少styled-components的文章,但没怎么找到与我产生共鸣的,所以就自己写一篇了

在写业务代码的过程中经常遇到前端命名规则和后端接口返回不一致的情况,我们需要在代码中做很多烦人的转换,例如

fetch().thne(resp => {
  this.userName = resp.user_nick_name;
})

我们需要这种把user_nick_name转换为userName的适配代码,以便把后端的数据放到前端的各种组件和Store中,这种操作是一种映射,通this.userName = resp.user_nick_name;这句绑定前后端数据的映射关系。

思维稍微发散一下,你会发现,CSS和DOM之间不也是通过这种映射关系绑定才让样式生效的嘛!

<div class="red-button"></div>

上面这段代码的写法,DOM和CSS是完全分离的,我们通过class="red-button"这种方式将CSS样式中的key与DOM绑定到一起,让样式生效。
这样写有好处,样式和DOM分离,单独来看都比较便于维护。

但问题就出在class="red-button"这句绑定上,当我找.red-button具体的样式时,如果项目目录结构比较规范,还算方便的就能找到CSS的文件,然后在文件中搜.red-button,定位红色按钮的样式代码,还算OK。但如果项目目录结构不规范,.red-button可能被定义在整个工程的anywhere。这时候就麻烦了,我一般都会直接全局搜索,并不是那么的舒服。

这时候一定会有人说css-modules,它可以让你像引入js那样引入css为json对象。这样的话,css文件就好找了。

import styles from './style.css';

但你有没有想过,那我们为什么需要写div, 为什么要有绑定映射用的class=

有没有仔细思考过红色按钮最直接的表达方式是什么?答案很简单,就是一个红色按钮而已啊。

<RedButton />

我感觉在JSX或者在DOM上面不段的写className="button", calss="button", class={styles.button},这些重复的class=,这样显得挺笨拙的,不是么?

再看下面这段代码:

.red-button {
  color: red;
}
<div class="red-button"></div>

我们该把关注点放在DOM元素到底是一个div标签还是button标签吗?显然不是,这都是多余的东西。

用styled-components写,烦人的绑定过程消失了,再也见不到class=这种绑定样式的语法了。

const RedButton = styled.div`
  color: red;
`;
<RedButton />

这是我使用styled-components的原因,你的呢?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant