styled-components 运行原理

4,755 阅读3分钟

styled-components 结合 React 框架使用,能让其支持 CSS in JS 的写法。比如:

const Button = styled.button`
  color: grey;
`;

以上是 SC(styled-components 简称,下同)的一个简单用法,它很方便的创建了一个 Button 组件,然后你就可以在任何地方使用这个组件。

<Button>Test</Button>

这一切是怎么做到的呢?下面我们一步步拆解。

语法规则解释

有人可能对 SC 的怪异语法规则有些费解,它怎么做到直接在 styled 后面获得一个 dom 节点,然后又拼接上一个字符串呢?其实 styled.button 等同于 styled('button'),是一个柯里化后的函数,而函数后可以接模板字符串(两个反引号包起来部分``)是 ES6 的一个新语法特性,相关文档,比如我们可以如下使用函数来接收一个字符串。

const fun = (args)=>{
  console.log(args);  // [ 'Hello' ]
}
fun`Hello`

并且其间也可以加入表达式。

const fun = (args, exp)=>{
  console.log(args);  // [ 'Hello ', ', Hi~' ]
  console.log(exp); // World
}
const v = "World"
fun`Hello ${v}, Hi~`

可以加入表达式的特性衍生出了 SC 的一种更高级用法,比如以上的 button,如果加入一个背景属性,而此属性会根据 props 而变化,则可以写成以下样子。

const Button = styled.button`
  color: grey;
  background: ${props => props.background};
`;

刚刚有人可能好奇 styled.button 是怎么就等同于 styled('button') 的,其实也简单,SC 在倒入 styled 时把所有的 dom 节点柯里化后的函数都赋值给了 styled 的同名属性,这样就能使用上面的语法方式了,具体实现就是下面这段代码。

domElements.forEach(domElement => {
  styled[domElement] = styled(domElement);
});

组件创建过程

那我们在用 SC 的方式声明了一个 Button 组件后,SC 做了哪些操作呢? 1,首先生成一个 componentId,SC 会确保这个 id 是唯一的,大致就是全局 count 递增、hash、外加前缀的过程。hash 使用了 MurmurHash,hash 过后的值会被转成字符串。生成的 id 类似 sc-bdVaJa

componentId = getAlphabeticChar(hash(count))

2,在 head 中插入一个 style 节点,并返回 className;创建一个 style 的节点,然后塞入到 head 标签中,生成一个 className,并且把模板字符串中的 style 结合 className 塞入到这个 style 节点中。其中 insertRule 方法

evaluatedStyles 是获得到的 style 属性
const style = document.createElement("style");
// WebKit hack
style.appendChild(document.createTextNode(""));
document.head.appendChild(style); 
const className = hash(componentId + evaluatedStyles);
style.sheet.insertRule('.className { evaluatedStyles }', 0)

3,根据解析的 props 和 className 来创建这个 element。

const newElement = React.createElement(
  type,
  [props],
  [...children]
)
newElement.className = "第二部生成的节点"

结论

SC 整体原理还是比较简单的,由于直接用了 ES6 的的字符模板特性,对 style 和 props 部分的解析也比较快,由于需要在运行过程中不断动态创建 Element 并且创建 style 消耗了部分性能。使用过程中也有些要注意的地方,拿最初的 button 举例,如果每次点击那个 Button 都会改变一次 background,你会发现在点 200 次后,SC 会报一个 warning。

Over 200 classes were generated for component styled.button. 
Consider using the attrs method, together with a style object for frequently changed styles.
Example:
  const Component = styled.div.attrs({
    style: ({ background }) => ({
      background,
    }),
  })`width: 100%;`
<Component />

warning 表示创建了超过 200 个类,这是由于每次 background 变化都会生成新的 Element 导致的,此时我们按照提示可以优化成直接使用节点的 style 属性来修改样式,避免重复生成节点类。

styled.button.attrs({
  style: props => ({background: props.background})
})``

css in js 的写法有很多优势,此处就不多说了,影响大家使用的很重要一点是性能,SC 团队也一直对外宣称要不断改进性能,20年的 V5 版本做了很多提升,当然由于实现机制,所以再怎么优化也不可能达到原生写法的性能。如果有对性能要求很严的网站建议不要使用,如果想写的快写的爽,用 SC还是很不错的选择。 号称是 Beast Mode 的 V5 版本更新宣传