前言
在 Vue、Angular 项目中,官方都给出了书写 CSS 的解决方案。但是 React 不同,毕竟路由、状态管理什么的也没有啊。下面是 CSS 解决方案一览:
普通前端项目、Vue、Angular、React:
- sass(scss)、less
一般在 React 中使用:
- css modules
- css in js
- styled-components
一、常规项目
1.1 sass(scss)、less
一种组合式的 CSS 提供方案,有自己的语法,也有许多有帮助的函数。两者我都使用过,两者类似。
二、React 项目
2.1 css modules
一种独立的 CSS 方案,你可以像组件一样引入它,并使用它的部分样式。(在 webpack 中使用,需要 css-loader
)
index.css :
.title {
color: red;
}
Index.jsx :
import React from 'react';
import style from './index.css';
export default () => {
return (
<h1 className={style.title}>
Hello World
</h1>
);
};
2.2 css in js
在 React 使用的最多了,通过对象字面量的方式创建 CSS:
const Index=()=>{
const style={ //这里定义样式
color:"red",
fontSize:"12px"
}
return (
<div style={style}>Hello world</div> //使用
)
}
2.3 styled-components
一种使用模版字符串描述 CSS,使得样式和组件耦合在一起,形成所谓的样式组件。
比较通用的有styled-components
,其实还有其他的样式组件,在material-UI的第五个版本就出现了它自己的样式组件,这里讲styled-components
:
npm install --save styled-components
/* 创建了一个Wrapper样式组件,该组件渲染之后是一个div标签 */
const Wrapper = styled.div`
color: blue;
`;
/* Wrapper组件跟其余的react组件一样,只不过现在他们有了自己的样式 */
render(
<Wrapper>
Hello World!
</Wrapper>
);