Skip to content

React 文档

导读与全书目录表:见同目录 01-React 入门:简介·特性与设计范式.md 开头。


在 react 中使用 css

方式一:使用内联 style 样式

html
<div style={{backgroundColor: 'red'}}>hello world</div>

方式二:import 普通 css 文件

  1. 创建 src/style/test.css 文件
css
.container {
  background-color: red;
}
  1. 在 JSX 模板中 import 引入并使用
html
import '@/style/test.css'
<div className={'container'}>hello world</div>

方式三:使用 CSS Modules

  1. 创建 test.module.css 文件
css
.container {
  background-color: red;
}
  1. 在 JSX 模板中 import 引入并作为对象使用
html
import styles from '@/style/test.module.css'
<div className={styles.container}>hello world</div>

方式四:使用 CSS-in-JS 方案

  1. 安装 pnpm install styled-components -S
  2. 在 JSX 模板中使用
js
import styled from 'styled-components';

// 创建一个带样式的按钮组件
const Button = styled.button`
  background: palevioletred;
  color: white;
  font-size: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
  cursor: pointer;

  &:hover {
    background: white;
    color: palevioletred;
  }
`;

function FunctionLi() {
  return (
    <>
      <Button>自定义按钮</Button>
    </>
  );
}

export default FunctionLi;

方式五:使用 scss

  1. 安装 pnpm install sass -D
  2. 在 jSX 模板中通过 import 引入 scss 文件

方式六:使用 Tailwind CSS

  1. 安装 Tailwind CSS 及相关依赖
shell
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
  1. 配置 Tailwind CSS,编辑 tailwind.config.js 文件,指定需要扫描的文件路径
js
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
  1. 在 CSS 中引入 Tailwind 指令,创建或编辑 src/index.css 文件,添加以下内容
css
@tailwind base;
@tailwind components;
@tailwind utilities;
  1. 在组件中
jsx
<p className="text-gray-600 mb-8 text-center"> 这是一个使用 Tailwind CSS 样式的 React 组件示例 </p>

总结

  1. 使用 css 的六种方式:内联 style、css、CSS Modules、scss、Styled-components (CSS-in-JS)、Tailwind CSS
  2. 小型项目可以使用:内联 style、css 文件、CSS Modules 文件
  3. 大型项目可以使用:scss、Styled-components (CSS-in-JS)、Tailwind CSS
  4. 每种方式特点:
  • 内联 style:无法使用伪类、伪元素和媒体查询
  • css:全局作用域容易造成命名冲突
  • CSS Modules:局部作用域,对象写法
  • scss:支持变量、嵌套、混合等高级功能
  • Styled-components:组件化,主题支持、样式隔离、动态样式、全局样式
  • Tailwind CSS:工具类优先,适合设计体系统一、快速迭代(是否采用看团队规范)

react 中引入 css 的几种方式

回答

shell
共有 8 种引入方式
1. 传统的通过 import 引入全局 css 文件
2. CSS Modules(模块化 CSS,React 官方推荐):将 CSS 文件命名为 [组件名].module.css,在组件中通过 import 导入并作为对象使用
3. 行内样式(内联样式):直接在 JSX 元素上通过 style 属性写样式,适合动态样式(根据状态 / 属性变化) 或临时样式
4.  CSS-in-JS 库(如 styled-components)
5.  预处理器(Sass/Scss/Less)

在 react 中获取 DOM

在函数组件中

  1. 在函数内的最外层,使用 useRef(null) 创建 ref
  2. 在 JSX 模板中,将 ref 绑定到 JSX 元素
  3. 在指定位置使用,比如 useEffect 中访问 DOM
ts
import { useRef, useEffect } from 'react';

function MyComponent() {
  // 1. 创建 ref
  const myRef = useRef(null);

  useEffect(() => {
    // 3. 在组件挂载后访问 DOM 元素
    console.log(myRef.current); // 这是实际的 DOM 节点
    
    if (myRef.current) {
      myRef.current.focus(); // 例如:让输入框自动获取焦点
    }
  }, []);

  // 2. 将 ref 绑定到 JSX 元素
  return <input ref={myRef} type="text" />;
}

在类组件中

  1. 在 constructor 中,使用 React.createRef() 创建 ref
  2. 在 JSX 模板中,将 ref 绑定到 JSX 元素上
  3. 在指定位置使用,比如 componentDidMount 中访问 DOM
ts
class MyComponent extends React.Component {
   constructor(props) {
      super(props);
      // 1、创建 ref
      this.myRef = React.createRef();
   }

   componentDidMount() {
      // 3、访问 DOM 元素
      console.log(this.myRef.current);
      this.myRef.current.focus(); // 例如聚焦到输入框
   }

   render() {
       // 将 ref 绑定到 JSX 元素
      return <input ref={this.myRef} />;
   }
}

总结

  1. 在函数组件中使用 useRef(null) 获取 DOM
  2. 再类组件中使用 React.createRef() 获取 DOM(React 16.3+ 推荐方式)
  3. 类组件中,在 componentDidMount 或 componentDidUpdate 生命周期方法中访问 ref,因为此时 DOM 已经渲染完成

react 中 mock 数据

实现原理

  • 通过 mockjs 创建 mock 服务,通过 Mock.mock 创建 mock 路由和访问的数据
  • 然后 axios 直接请求 mock 的路由即可,获取对应的 json 数据

集成过程

  1. 安装
shell
pnpm install mockjs -D
  1. 在入口文件 main.js 中运行 mockServe
ts
// 如果注释则不使用 mock,而是使用接口数据 
import "./mock/mockServe.js";
  1. 定义 mockServe 程序
ts
// 在 src/mock/mockServe.js 中
import Mock from "mockjs";

import info from "./api/user/info.json";
import login from "./api/user/login.json";

Mock.setup({
  timeout: "100-1000",
});

// user 模块
Mock.mock("/api/user/info", info);
Mock.mock("/api/user/login", login);
  1. 定义存储数据的 json 文件
ts
// 在 src/mock/api/user/info.json 中
{
  "code": 200,
  "data": {
    "name": "zhangsan",
    "age": 20
  }
}
  1. axios 请求时的 url ,直接指向 mock 的路由
ts
// 在 src/api/user.js 中
import request from "../utils/request";

export function login(data) {
  return request({
    url: "/api/user/login",
    method: "post",
    data,
  });
}

export function getInfo(params) {
  return request({
    url: "/api/user/info",
    method: "get",
    params,
  });
}