【REACT】CSS in JS 将样式写在JS、JSX中
在react开发过程中,我们已经将html和js写到了同一个文件中(js、jsx),而样式我们还需要写样式文件单独引入, 这个过程中如果没做好模块化,则可能会造成类名全局污染。
比如有一个单文件组件
Button.js
import React from 'react';
import '../button.styles.css' // 引入样式
export default function (){
return <button className="pink_button">button</button>
}
或者使用模块化的
import React from 'react';
import styles from '../button.styles.css' // 引入样式
export default function (){
return <button className={styles.pink_button}>button</button>
}
css in js 的出现使得我们可以直接在单一个组件文件中写html、js、css, 这有利于组件的隔离。每个组件包含了所有需要用到的代码, 不依赖外部,组件之间没有耦合,很方便复用。这正是发挥了react的优势和特性。
上述代码使用css-in-js方案可以改写成
import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background: palevioletred;
color: white;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
outline: none;
`;
export default Button;
本文主要介绍我自己使用过的以及下载量较高的几个库。
styled-components
使用起来非常简单,功能强大,而且使用量大。
@emotion/styled
该库灵感来自styled-components,功能上更加强大,针对react有更多的特色。该作者还有其它库,可供选择的非常多。
@jss
可能是css in js 的鼻祖了。如果语法不懂,直接看这里的API就可以了
当然css-in-js的写法和功能不仅于此,跟多的用法和功能请查看对应库的文档。Thank you for your watch