styled-components 结合 React 框架使用,能让其支持 CSS in JS 的写法。好比:css
const Button = styled.button`
color: grey;
`;
复制代码
以上是 SC
(styled-components 简称,下同)的一个简单用法,它很方便的建立了一个 Button 组件,而后你就能够在任何地方使用这个组件。git
<Button>Test</Button>
复制代码
这一切是怎么作到的呢?下面咱们一步步拆解。github
有人可能对 SC
的怪异语法规则有些费解,它怎么作到直接在 styled 后面得到一个 dom 节点,而后又拼接上一个字符串呢?其实 styled.button 等同于 styled('button'),是一个柯里化后的函数,而函数后能够接模板字符串(两个反引号包起来部分``)是 ES6 的一个新语法特性,相关文档,好比咱们能够以下使用函数来接收一个字符串。bash
const fun = (args)=>{
console.log(args); // [ 'Hello' ]
}
fun`Hello`
复制代码
而且其间也能够加入表达式。app
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 的同名属性,这样就能使用上面的语法方式了,具体实现就是下面这段代码。dom
domElements.forEach(domElement => {
styled[domElement] = styled(domElement);
});
复制代码
那咱们在用 SC 的方式声明了一个 Button 组件后,SC 作了哪些操做呢? 1,首先生成一个 componentId,SC 会确保这个 id 是惟一的,大体就是全局 count 递增、hash、外加前缀的过程。hash 使用了 MurmurHash,hash 事后的值会被转成字符串。生成的 id 相似 sc-bdVaJa
ide
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 版本更新宣传