1.在组件内直接使用
直接在组件中书写css样式,通过style属性直接引入,如下:
import React, { Component } from "react";const div1 = {width: "300px",margin: "30px auto",backgroundColor: "#44014C", //驼峰法minHeight: "200px",boxSizing: "border-box"};class Test extends Component {constructor(props, context) {super(props);}render() {return (<div><div style={div1}>123</div><div style={{backgroundColor:"red"}}></div>);}}
2.组件中引入css文件
将css单独写在一个css文件中,然后在组件中直接引入
这种方式存在不好的地方在于样式是全局生效,样式之间会互相影响
3.在组件中引入.module.css文件
将css文件作为一个模块引入,这个模块中的所有css,只作用于当前组件。不会影响当前组件的后代组件
这种方式是webpack特工的方案,只需要配置webpack配置文件中modules:true即可
4.CSS in JS
CSS-in-JS, 是指一种模式,其中CSS由 JavaScript 生成而不是在外部文件中定义
此功能并不是 React 的一部分,而是由第三方库提供,例如:
- styled-components
- emotion
- glamorous
