Article
第一章:Material-UI 简介
1.1 什么是 Material-UI
| 概念名称 | 说明 | 注意事项 |
|---|---|---|
| Material-UI | 一个基于 Google Material Design 的 React UI 组件库,提供预构建的组件以加速开发。 | 不同于 Google 官方的 Material Design 实现,它是社区维护的开源项目。 |
| Material Design | 由 Google 开发的设计语言,强调卡片、网格、响应式动画和过渡、填充深度和光线等视觉效果。 | 学习 Material Design 原则有助于更好地使用 Material-UI。 |
| React 组件库 | 提供可复用的 UI 组件,与 React 生态无缝集成,支持 JSX 语法和 React 状态管理。 | 需具备基本的 React 知识(如组件、Props、State)才能有效使用。 |
| 开源项目 | 在 MIT 许可下开源,由社区维护和贡献,定期更新和修复问题。 | 可查看 GitHub 仓库获取最新版本和提交问题。 |
1.2 安装和设置
| 方法名称 | 语法/命令 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| npm 安装 | npm install @mui/material @emotion/react @emotion/styled | 通过 npm 包管理器安装 Material-UI 核心库及其样式依赖(Emotion)。 | npm install @mui/material @emotion/react @emotion/styled | 确保 Node.js 版本 >= 10.0.0,Emotion 是默认样式引擎。 |
| yarn 安装 | yarn add @mui/material @emotion/react @emotion/styled | 通过 Yarn 包管理器安装 Material-UI 核心库及其样式依赖。 | yarn add @mui/material @emotion/react @emotion/styled | 与 npm 等效,根据项目包管理器选择。 |
| 字体引入 | <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> | 在 HTML 中引入 Roboto 字体,确保组件文本显示符合 Material Design。 | <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> | 必须添加到 public/index.html 或类似文件,否则字体可能不生效。 |
| 图标引入 | <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> | 在 HTML 中引入 Material Icons,用于图标组件。 | <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> | 如果使用 Icon 组件,此步骤是必需的。 |
| 项目初始化 | 无特定语法,需在 React 应用根组件中导入 Material-UI 组件。 | 设置 React 应用以使用 Material-UI 组件。 | import Button from '@mui/material/Button'; function App() { return <Button variant="contained">Hello World</Button>; } | 确保 React 版本 >= 16.8.0,以支持 Hooks。 |
1.3 第一个 Material-UI 应用
| 方法名称 | 语法/命令 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| 创建 React 应用 | npx create-react-app my-app | 使用 Create React App 脚手架快速初始化一个新的 React 项目。 | npx create-react-app my-app | 需要 Node.js 环境,my-app 为项目名称,可自定义。 |
| 安装 Material-UI | cd my-app && npm install @mui/material @emotion/react @emotion/styled | 在 React 项目中安装 Material-UI 依赖。 | cd my-app && npm install @mui/material @emotion/react @emotion/styled | 安装后重启开发服务器(如 npm start)。 |
| 添加字体和图标 | 在 public/index.html 的 <head> 中添加链接。 | 引入 Roboto 字体和 Material Icons 以确保样式正确。 | <head><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /></head> | 如果忘记添加,组件可能使用默认字体而非 Roboto。 |
| 使用按钮组件 | import Button from '@mui/material/Button'; | 在组件中导入并使用 Material-UI 的 Button 组件创建一个简单 UI。 | import React from 'react'; import Button from '@mui/material/Button'; function App() { return ( <div><Button variant="contained">Click Me</Button></div> ); } export default App; | variant="contained" 是按钮的样式变体,其他变体包括 "text" 和 "outlined"。 |
| 运行应用 | npm start | 启动开发服务器,在浏览器中预览应用。 | npm start | 默认在 http://localhost:3000 打开,确保端口未被占用。 |
第二章:核心概念
2.1 主题(Theme)
| 概念/方法名称 | 语法/说明 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| ThemeProvider | import { ThemeProvider, createTheme } from '@mui/material/styles'; | 提供主题给组件树中的所有组件,实现全局样式统一。 | const theme = createTheme(); function App() { return ( <ThemeProvider theme={theme}> <Button>Test</Button> </ThemeProvider> ); } | 必须包裹在组件树的根部,否则子组件无法获取主题。 |
| createTheme | createTheme(options?) | 创建自定义主题对象,可覆盖默认的主题设置。 | const theme = createTheme({ palette: { primary: { main: '#1976d2' } } }); | options 参数可选,支持嵌套配置(palette、typography 等)。 |
| useTheme Hook | const theme = useTheme(); | 在函数组件中访问当前主题对象。 | function MyComponent() { const theme = useTheme(); return <div style={{ color: theme.palette.primary.main }}>Text</div>; } | 只能在 ThemeProvider 的子组件中使用,否则返回默认主题。 |
| 主题选项 | 对象属性如 palette、typography、spacing | 配置主题的各个方面,包括调色板、字体、间距等。 | const theme = createTheme({ palette: { primary: { main: '#ff0000' } }, typography: { fontSize: 14 } }); | 主题选项遵循特定结构,错误的属性名可能被忽略。 |
| 默认主题 | Material-UI 内置的预定义主题 | 提供开箱即用的设计系统,无需额外配置。 | import { createTheme } from '@mui/material/styles'; const defaultTheme = createTheme(); | 默认主题基于 Material Design 指南,可直接使用或扩展。 |
2.2 样式解决方案(Styled Components)
| 概念/方法名称 | 语法/说明 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| styled API | import { styled } from '@mui/material/styles'; | 创建带有自定义样式的组件,基于 Emotion 样式引擎。 | const MyButton = styled(Button)({ backgroundColor: 'red', '&:hover': { backgroundColor: 'blue' } }); | 支持 CSS 字符串和对象语法,样式作用域限于该组件。 |
| sx prop | <Box sx={{ ...styles }} /> | 在组件上直接应用内联样式,支持主题感知和响应式值。 | <Box sx={{ color: 'primary.main', fontSize: { xs: 12, md: 16 } }} /> | 性能优于 styled API 的简单样式,但复杂样式建议使用 styled。 |
| CSS 对象 | { property: value } | 使用 JavaScript 对象表示 CSS 样式,可与 styled 或 sx 配合使用。 | const styles = { root: { padding: 2 }, title: { fontSize: 14 } }; | 属性名使用 camelCase(如 backgroundColor 而非 background-color)。 |
| 主题访问 | ({ theme }) => value | 在样式函数中访问主题变量,实现主题一致的样式。 | const MyComponent = styled('div')(({ theme }) => ({ padding: theme.spacing(2), color: theme.palette.primary.main })); | 确保 theme 参数正确传递,否则可能返回 undefined。 |
| 响应式样式 | { xs: value, md: value } | 根据断点应用不同的样式值,实现响应式设计。 | <Box sx={{ width: { xs: '100%', md: '50%' } }} /> | 断点键(xs、sm、md、lg、xl)对应不同的屏幕宽度。 |
2.3 响应式设计
| 概念/方法名称 | 语法/说明 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| 断点系统 | xs: 0px, sm: 600px, md: 900px, lg: 1200px, xl: 1536px | 定义不同屏幕尺寸的阈值,用于响应式布局和样式。 | const theme = createTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536 } } }); | 可自定义断点值,但需确保与 Material-UI 组件兼容。 |
| useMediaQuery Hook | const matches = useMediaQuery(query); | 检测当前屏幕尺寸是否匹配媒体查询,用于条件渲染。 | function MyComponent() { const matches = useMediaQuery('(min-width:600px)'); return <div>{matches ? 'Desktop' : 'Mobile'}</div>; } | 查询字符串需符合 CSS 媒体查询语法,支持主题断点。 |
| Grid 组件 | <Grid container spacing={2}> | 创建响应式网格布局,自动适应不同屏幕尺寸。 | <Grid container spacing={2}><Grid item xs={12} md={6}><Paper>Content</Paper></Grid><Grid item xs={12} md={6}><Paper>Content</Paper></Grid></Grid> | xs、sm 等属性定义在不同断点下的列数(共 12 列)。 |
| 容器组件 | <Container maxWidth="md"> | 包装内容并提供最大宽度约束,实现页面居中布局。 | <Container maxWidth="md"><Box sx={{ bgcolor: 'grey.100' }}>Content</Box></Container> | maxWidth 可选 "xs"、"sm"、"md"、"lg"、"xl" 或 false(无约束)。 |
| 隐藏组件 | <Hidden mdDown><Component /></Hidden> | 根据断点条件性地隐藏或显示组件。 | <Hidden mdDown><div>只在大于 md 断点时显示</div></Hidden> | 已弃用,推荐使用 useMediaQuery 或 sx prop 实现类似功能。 |
第三章:基本组件
3.1 按钮(Button)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Button 组件 | <Button>文本</Button> | 创建可点击的按钮,支持多种样式和功能。 | import Button from '@mui/material/Button'; <Button>点击我</Button> | 必须导入 Button 组件才能使用。 |
| variant 属性 | variant="text" | "outlined" | "contained" | 定义按钮的视觉变体样式。 | <Button variant="contained">实心按钮</Button><Button variant="outlined">描边按钮</Button><Button variant="text">文本按钮</Button> | contained 是强调按钮,outlined 是中等强调,text 是低强调。 |
| color 属性 | color="primary" | "secondary" | "success" | "error" | "info" | "warning" | 设置按钮的颜色主题。 | <Button color="primary">主要</Button><Button color="secondary">次要</Button><Button color="error">错误</Button> | 默认 primary,可扩展主题添加自定义颜色。 |
| size 属性 | size="small" | "medium" | "large" | 控制按钮的尺寸大小。 | <Button size="small">小按钮</Button><Button size="large">大按钮</Button> | medium 是默认尺寸。 |
| disabled 属性 | disabled={true | false} | 禁用按钮,使其不可点击。 | <Button disabled>禁用按钮</Button> | 禁用时按钮会变灰并阻止点击事件。 |
| startIcon / endIcon | startIcon={<Icon>} endIcon={<Icon>} | 在按钮文本前后添加图标。 | <Button startIcon={<SaveIcon />}>保存</Button><Button endIcon={<SendIcon />}>发送</Button> | 需要先导入对应的图标组件。 |
| onClick 事件 | onClick={(event) => {}} | 处理按钮点击事件。 | <Button onClick={() => alert('点击!')}>点击</Button> | 与其他 React 事件处理程序用法相同。 |
| href 属性 | href="url" | 将按钮转换为链接按钮。 | <Button href="#about">关于我们</Button> | 设置后按钮会渲染为 <a> 元素。 |
3.2 图标(Icon)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Icon 组件 | <Icon>icon_name</Icon> | 显示 Material Icons 字体图标。 | import Icon from '@mui/material/Icon'; <Icon>star</Icon> | 需要预先引入 Material Icons 字体链接。 |
| Material Icons | <Icon>icon_name</Icon> | 使用 Material Icons 字体中的特定图标。 | <Icon>home</Icon><Icon>favorite</Icon><Icon>delete</Icon> | 图标名称对应 Material Icons 字体中的字符代码。 |
| SvgIcon 组件 | <SvgIcon>svg_path</SvgIcon> | 显示 SVG 图标,支持自定义 SVG 路径。 | import SvgIcon from '@mui/material/SvgIcon'; <SvgIcon>{/* SVG 路径 */}</SvgIcon> | 用于自定义 SVG 图标或非 Material Icons。 |
| IconButton 组件 | <IconButton><Icon /></IconButton> | 创建可点击的图标按钮,通常用于操作。 | import IconButton from '@mui/material/IconButton'; <IconButton><Icon>menu</Icon></IconButton> | 提供适当的点击目标和悬停效果。 |
| color 属性 | color="primary" | "secondary" | "action" | "error" | "disabled" | 设置图标的颜色主题。 | <Icon color="primary">home</Icon><IconButton color="secondary"><Icon>favorite</Icon></IconButton> | 在 IconButton 中,color 影响图标的颜色。 |
| fontSize 属性 | fontSize="small" | "medium" | "large" | "inherit" | 控制图标的大小。 | <Icon fontSize="small">star</Icon><Icon fontSize="large">home</Icon> | inherit 会继承父元素的字体大小。 |
| 自定义图标 | 使用 SvgIcon 包装 SVG | 创建和使用自定义 SVG 图标。 | const HomeIcon = (props) => (<SvgIcon {...props}>{/* 自定义 SVG 路径 */}</SvgIcon>); | 确保 SVG 路径正确,视图框设置适当。 |
3.3 排版(Typography)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Typography 组件 | <Typography>文本</Typography> | 显示文本内容,应用一致的字体样式。 | import Typography from '@mui/material/Typography'; <Typography>Hello World</Typography> | 替代原生 HTML 文本元素,提供更好的主题集成。 |
| variant 属性 | variant="h1" | "h2" | "body1" | "button" | "caption" | 定义文本的语义样式变体。 | <Typography variant="h1">标题1</Typography><Typography variant="body1">正文</Typography><Typography variant="button">按钮文本</Typography> | 映射到 HTML 标题元素(h1-h6)或语义文本元素。 |
| component 属性 | component="h1" | "div" | "span" | 指定底层渲染的 HTML 元素。 | <Typography variant="h1" component="h2">看起来像h1,实际是h2</Typography><Typography component="span">内联文本</Typography> | 允许分离视觉样式和语义结构。 |
| align 属性 | align="left" | "center" | "right" | "justify" | 控制文本的水平对齐方式。 | <Typography align="center">居中文本</Typography><Typography align="right">右对齐文本</Typography> | 只影响块级容器内的文本对齐。 |
| color 属性 | color="primary" | "textPrimary" | "error" | "inherit" | 设置文本颜色,支持主题颜色。 | <Typography color="primary">主要颜色文本</Typography><Typography color="textSecondary">次要文本</Typography> | textPrimary 和 textSecondary 是主题中的文本颜色变量。 |
| gutterBottom 属性 | gutterBottom={true | false} | 添加底部外边距,用于段落间距。 | <Typography gutterBottom>有底部间距的段落</Typography> | 常用于标题和段落之间创建视觉分隔。 |
| noWrap 属性 | noWrap={true | false} | 防止文本换行,溢出时显示省略号。 | <Typography noWrap>很长很长不会换行的文本...</Typography> | 需要设置固定宽度或父容器宽度,否则无效。 |
| 字体样式属性 | fontWeight="bold" fontStyle="italic" | 通过 sx prop 控制字体粗细和样式。 | <Typography sx={{ fontWeight: 'bold', fontStyle: 'italic' }}>粗体斜体</Typography> | 这些样式也可以通过主题统一配置。 |
第四章:布局组件
4.1 网格(Grid)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Grid 容器 | <Grid container></Grid> | 创建网格布局的容器,包含一行或多行网格项。 | <Grid container spacing={2}><Grid item>内容1</Grid><Grid item>内容2</Grid></Grid> | container 属性使 Grid 成为 flex 容器。 |
| Grid 项 | <Grid item></Grid> | 在网格容器中创建单个网格项。 | <Grid container><Grid item>网格项</Grid></Grid> | item 属性必须用于容器内的直接子元素。 |
| spacing 属性 | spacing={0-10} | 设置网格项之间的间距(以 8px 为基数)。 | <Grid container spacing={2}><Grid item>有间距</Grid></Grid> | spacing={2} 表示 16px 间距,支持 0-10 的整数。 |
| xs/sm/md/lg/xl | xs={1-12} | 在不同断点下设置网格项占据的列数(12 列网格)。 | <Grid item xs={12} md={6}>移动端全宽,桌面端半宽</Grid> | 数值 1-12 或 true(自动宽度),false(隐藏)。 |
| direction 属性 | direction="row" | "column" | 设置网格容器的主轴方向。 | <Grid container direction="row"><Grid item>水平排列</Grid></Grid> | 默认为 row,可设置为 column 进行垂直排列。 |
| justifyContent | justifyContent="flex-start" | "center" | "flex-end" | "space-between" | "space-around" | "space-evenly" | 设置网格项在主轴上的对齐方式。 | <Grid container justifyContent="center"><Grid item>居中</Grid></Grid> | 类似于 CSS justify-content 属性。 |
| alignItems | alignItems="flex-start" | "center" | "flex-end" | "stretch" | "baseline" | 设置网格项在交叉轴上的对齐方式。 | <Grid container alignItems="center"><Grid item>垂直居中</Grid></Grid> | 类似于 CSS align-items 属性。 |
| wrap 属性 | wrap="nowrap" | "wrap" | "wrap-reverse" | 控制网格项是否换行显示。 | <Grid container wrap="wrap"><Grid item>允许换行</Grid></Grid> | 默认为 wrap,nowrap 会强制单行显示。 |
4.2 容器(Container)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Container 组件 | <Container></Container> | 包装页面内容,提供最大宽度约束和水平居中。 | <Container>页面内容</Container> | 默认有左右内边距,可通过 disableGutters 禁用。 |
| maxWidth 属性 | maxWidth="xs" | "sm" | "md" | "lg" | "xl" | false | 设置容器的最大宽度。 | <Container maxWidth="md">中等宽度容器</Container> | false 表示无最大宽度限制,会扩展到全宽。 |
| fixed 属性 | fixed={true | false} | 设置固定最大宽度而非响应式宽度。 | <Container fixed maxWidth="md">固定宽度容器</Container> | 固定宽度在不同断点下不会改变。 |
| disableGutters | disableGutters={true | false} | 移除容器的左右内边距。 | <Container disableGutters>无边距内容</Container> | 默认有内边距,禁用后内容会贴边。 |
| sx 属性 | sx={{ custom styles }} | 应用自定义样式到容器。 | <Container sx={{ bgcolor: 'grey.100' }}>自定义背景</Container> | 支持所有系统属性如 padding、margin 等。 |
4.3 盒子(Box)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Box 组件 | <Box></Box> | 作为通用包装器组件,用于分组和样式应用。 | <Box>任意内容</Box> | 默认渲染为 <div> 元素。 |
| component 属性 | component="span" | "section" | "main" | 指定 Box 渲染的 HTML 元素。 | <Box component="span">内联元素</Box> | 支持任何有效的 HTML 元素或 React 组件。 |
| sx 属性 | sx={{ property: value }} | 应用样式系统属性,支持主题和响应式值。 | <Box sx={{ color: 'primary.main', p: 2, m: 1 }}>样式盒子</Box> | 使用系统属性简写(p=padding,m=margin)。 |
| 系统属性 | p, m, bgcolor, color, width, height | 通过 sx 或直接属性应用样式系统。 | <Box p={2} m={1} bgcolor="primary.main">系统属性</Box> | 数值对应主题 spacing 倍数,如 p={2} = 16px。 |
| 显示属性 | display="flex" | "grid" | "none" | 设置 Box 的显示类型。 | <Box display="flex">flex 容器</Box> | 支持所有 CSS display 值。 |
| 定位属性 | position="absolute" | "relative" | "fixed" | 设置 Box 的定位方式。 | <Box position="absolute" top={0}>绝对定位</Box> | 配合 top、right、bottom、left 使用。 |
| 边框和阴影 | border={1} boxShadow={2} | 应用边框和阴影效果。 | <Box border={1} borderColor="grey.300" boxShadow={2}>带边框阴影</Box> | 数值对应主题中的阴影级别(0-24)。 |
| 响应式值 | sx={{ width: { xs: 1, md: 1/2 } }} | 在不同断点下应用不同的样式值。 | <Box sx={{ width: { xs: '100%', md: '50%' } }}>响应式宽度</Box> | 支持所有系统属性的响应式配置。 |
第五章:表单组件
5.1 文本字段(TextField)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| TextField 组件 | <TextField /> | 创建文本输入字段,集成标签、输入框和错误状态。 | <TextField label="姓名" variant="outlined" /> | 是 Input、FormControl 等组件的组合封装。 |
| variant 属性 | variant="outlined" | "filled" | "standard" | 设置文本字段的视觉变体样式。 | <TextField variant="outlined" /><TextField variant="filled" /><TextField variant="standard" /> | outlined 带边框,filled 带背景色,standard 是下划线样式。 |
| label 属性 | label="标签文本" | 设置文本字段的标签文字。 | <TextField label="邮箱地址" /> | 标签会在获得焦点时上浮或缩小。 |
| value 和 onChange | value={value} onChange={handleChange} | 控制文本字段的值和变化处理。 | const [value, setValue] = useState(''); <TextField value={value} onChange={(e) => setValue(e.target.value)} /> | 必须配合状态管理使用,实现受控组件。 |
| type 属性 | type="text" | "password" | "email" | "number" | 设置输入框类型,影响输入验证和键盘类型。 | <TextField type="password" /><TextField type="email" /> | 默认为 text,设置特定类型会有相应的浏览器验证。 |
| required 属性 | required={true | false} | 标记字段为必填项,显示星号标识。 | <TextField required label="必填字段" /> | 需要配合验证逻辑,本身只提供视觉提示。 |
| error 和 helperText | error helperText="错误提示" | 显示错误状态和错误提示信息。 | <TextField error helperText="请输入有效内容" /> | error 为 true 时显示红色边框和错误样式。 |
| disabled 属性 | disabled={true | false} | 禁用文本字段,使其不可编辑。 | <TextField disabled label="禁用字段" /> | 禁用时输入框变灰,阻止用户交互。 |
| fullWidth 属性 | fullWidth={true | false} | 使文本字段占据父容器的全部宽度。 | <TextField fullWidth label="全宽字段" /> | 常用于表单中需要填满可用空间的情况。 |
| size 属性 | size="small" | "medium" | 控制文本字段的尺寸。 | <TextField size="small" label="小尺寸" /> | small 提供更紧凑的输入框。 |
5.2 选择框(Select)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Select 组件 | <Select></Select> | 创建下拉选择框,允许用户从选项列表中选择。 | <Select value={age}><MenuItem value={10}>十岁</MenuItem></Select> | 必须与 MenuItem 组件配合使用。 |
| value 属性 | value={selectedValue} | 设置或获取当前选中的值。 | const [age, setAge] = useState(''); <Select value={age} onChange={handleChange}> | 需要状态管理来实现受控组件。 |
| onChange 事件 | onChange={(event) => {}} | 处理选择变化事件。 | const handleChange = (event) => { setAge(event.target.value); }; | event.target.value 包含选中项的值。 |
| MenuItem 组件 | <MenuItem value={value}></MenuItem> | 定义选择框中的选项。 | <MenuItem value={10}>十</MenuItem><MenuItem value={20}>二十</MenuItem> | 每个 MenuItem 代表一个可选项。 |
| label 属性 | label="选择标签" | 为选择框添加标签。 | <InputLabel>年龄</InputLabel><Select><MenuItem>选项</MenuItem></Select> | 通常与 InputLabel 组件配合使用。 |
| native 属性 | native={true | false} | 使用原生 HTML select 元素而非自定义实现。 | <Select native><option value={10}>十</option></Select> | 性能更好,但样式自定义能力有限。 |
| multiple 属性 | multiple={true | false} | 启用多选模式,允许选择多个值。 | <Select multiple value={selectedValues}><MenuItem value={1}>A</MenuItem></Select> | value 应该是数组类型,显示选中的多个值。 |
| displayEmpty 属性 | displayEmpty={true | false} | 在没有选中值时显示空状态提示。 | <Select displayEmpty><MenuItem value="">请选择</MenuItem></Select> | 配合空值的 MenuItem 使用。 |
5.3 复选框(Checkbox)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Checkbox 组件 | <Checkbox /> | 创建复选框输入,允许用户选择多个选项。 | <Checkbox checked={checked} onChange={handleChange} /> | 支持选中、未选中和不确定三种状态。 |
| checked 属性 | checked={true | false} | 设置复选框的选中状态。 | const [checked, setChecked] = useState(false); <Checkbox checked={checked} /> | 必须配合 onChange 实现受控组件。 |
| onChange 事件 | onChange={(event, checked) => {}} | 处理复选框状态变化。 | const handleChange = (event) => { setChecked(event.target.checked); }; | event.target.checked 表示新的选中状态。 |
| indeterminate 属性 | indeterminate={true | false} | 设置复选框为不确定状态(部分选中)。 | <Checkbox indeterminate checked={false} /> | 常用于树形结构中表示部分子项被选中。 |
| color 属性 | color="primary" | "secondary" | "success" | "default" | 设置复选框的颜色主题。 | <Checkbox color="primary" /><Checkbox color="secondary" /> | 默认 primary,支持主题中的调色板颜色。 |
| FormControlLabel | <FormControlLabel control={<Checkbox />} label="标签" /> | 为复选框添加标签和正确布局。 | <FormControlLabel control={<Checkbox />} label="我同意条款" /> | 提供可点击的标签区域,提升用户体验。 |
| disabled 属性 | disabled={true | false} | 禁用复选框,使其不可交互。 | <Checkbox disabled /> | 禁用时复选框变灰,阻止用户操作。 |
| size 属性 | size="small" | "medium" | 控制复选框的尺寸。 | <Checkbox size="small" /> | small 提供更紧凑的复选框。 |
5.4 单选框(Radio)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Radio 组件 | <Radio /> | 创建单选框输入,允许用户从多个选项中选择一个。 | <Radio checked={selected} onChange={handleChange} /> | 同一组的单选框应该共享相同的 name 属性。 |
| checked 属性 | checked={true | false} | 设置单选框的选中状态。 | const [selected, setSelected] = useState(false); <Radio checked={selected} /> | 同一时间同一组中只有一个可为 true。 |
| onChange 事件 | onChange={(event) => {}} | 处理单选框选择变化事件。 | const handleChange = (event) => { setSelected(event.target.checked); }; | event.target.checked 表示新的选中状态。 |
| RadioGroup 组件 | <RadioGroup></RadioGroup> | 将多个单选框分组管理,确保互斥选择。 | <RadioGroup value={value} onChange={handleChange}><Radio value="a" /><Radio value="b" /></RadioGroup> | 自动管理组内单选框的互斥行为。 |
| FormControlLabel | <FormControlLabel control={<Radio />} label="标签" value="值" /> | 为单选框添加标签和正确布局。 | <FormControlLabel value="a" control={<Radio />} label="选项A" /> | 在 RadioGroup 中使用时需提供 value 属性。 |
| color 属性 | color="primary" | "secondary" | "success" | "default" | 设置单选框的颜色主题。 | <Radio color="primary" /><Radio color="secondary" /> | 默认 primary,支持主题中的调色板颜色。 |
| row 属性 | row={true | false} | 在 RadioGroup 中水平排列单选框。 | <RadioGroup row><FormControlLabel value="a" control={<Radio />} label="A" /></RadioGroup> | 默认为垂直排列,row 设置为水平排列。 |
| disabled 属性 | disabled={true | false} | 禁用单选框,使其不可选择。 | <Radio disabled /> | 禁用时单选框变灰,阻止用户选择。 |
5.5 开关(Switch)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Switch 组件 | <Switch /> | 创建切换开关,用于打开/关闭或启用/禁用设置。 | <Switch checked={checked} onChange={handleChange} /> | 提供视觉反馈,常用于设置布尔值。 |
| checked 属性 | checked={true | false} | 设置开关的打开/关闭状态。 | const [checked, setChecked] = useState(false); <Switch checked={checked} /> | true 表示打开状态,false 表示关闭状态。 |
| onChange 事件 | onChange={(event, checked) => {}} | 处理开关状态变化事件。 | const handleChange = (event) => { setChecked(event.target.checked); }; | event.target.checked 表示新的开关状态。 |
| color 属性 | color="primary" | "secondary" | "success" | "default" | "warning" | "error" | 设置开关的颜色主题。 | <Switch color="primary" /><Switch color="secondary" /> | 默认 primary,支持主题中的调色板颜色。 |
| FormControlLabel | <FormControlLabel control={<Switch />} label="标签" /> | 为开关添加标签和正确布局。 | <FormControlLabel control={<Switch />} label="启用通知" /> | 提供可点击的标签区域,提升用户体验。 |
| size 属性 | size="small" | "medium" | 控制开关的尺寸。 | <Switch size="small" /> | small 提供更紧凑的开关。 |
| disabled 属性 | disabled={true | false} | 禁用开关,使其不可切换。 | <Switch disabled /> | 禁用时开关变灰,阻止用户操作。 |
| required 属性 | required={true | false} | 标记开关为必填项。 | <Switch required /> | 在表单验证中标记该开关必须被操作。 |
第六章:导航组件
6.1 应用栏(AppBar)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| AppBar 组件 | <AppBar></AppBar> | 创建顶部应用栏,通常包含标题、导航和操作项。 | <AppBar position="static"><Toolbar>标题</Toolbar></AppBar> | 通常与 Toolbar 组件配合使用以获得最佳布局。 |
| position 属性 | position="fixed" | "absolute" | "sticky" | "static" | "relative" | 设置应用栏的定位方式。 | <AppBar position="fixed">固定顶部</AppBar> | fixed 会固定在视口顶部,可能需要为内容添加 padding。 |
| color 属性 | color="default" | "primary" | "secondary" | "transparent" | "inherit" | 设置应用栏的背景颜色。 | <AppBar color="primary">主要颜色</AppBar> | default 使用默认背景色,transparent 为透明背景。 |
| Toolbar 组件 | <Toolbar></Toolbar> | 作为应用栏的内容容器,提供适当的间距和对齐。 | <AppBar><Toolbar>工具栏内容</Toolbar></AppBar> | 自动处理内容的水平排列和垂直居中。 |
| Typography 组件 | <Typography variant="h6"></Typography> | 在应用栏中显示标题文本。 | <Toolbar><Typography variant="h6">应用标题</Typography></Toolbar> | variant="h6" 通常用于应用栏标题。 |
| IconButton 组件 | <IconButton><Icon /></IconButton> | 在应用栏中添加图标按钮,用于菜单、搜索等操作。 | <IconButton color="inherit"><MenuIcon /></IconButton> | color="inherit" 使图标继承应用栏的文字颜色。 |
| sx 属性 | sx={{ custom styles }} | 应用自定义样式到应用栏。 | <AppBar sx={{ bgcolor: 'success.main' }}>自定义颜色</AppBar> | 支持所有系统属性和主题变量。 |
| enableColorOnDark | enableColorOnDark={true | false} | 在暗色主题下保持应用栏的颜色。 | <AppBar enableColorOnDark>暗色模式下保持颜色</AppBar> | 默认在暗色模式下应用栏会变暗。 |
6.2 抽屉(Drawer)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Drawer 组件 | <Drawer></Drawer> | 创建侧边导航抽屉,可从屏幕边缘滑入。 | <Drawer open={open} onClose={handleClose}>抽屉内容</Drawer> | 需要控制 open 状态来实现显示/隐藏。 |
| open 属性 | open={true | false} | 控制抽屉的打开和关闭状态。 | const [open, setOpen] = useState(false); <Drawer open={open}>内容</Drawer> | 必须配合状态管理使用。 |
| onClose 事件 | onClose={handleClose} | 处理抽屉关闭事件。 | const handleClose = () => { setOpen(false); }; <Drawer open={open} onClose={handleClose}> | 点击遮罩层或按 ESC 键时会触发。 |
| anchor 属性 | anchor="left" | "right" | "top" | "bottom" | 设置抽屉从哪个方向打开。 | <Drawer anchor="left">左侧抽屉</Drawer><Drawer anchor="right">右侧抽屉</Drawer> | 默认为 left,即从左侧打开。 |
| variant 属性 | variant="permanent" | "persistent" | "temporary" | 设置抽屉的变体类型。 | <Drawer variant="permanent">永久显示</Drawer> | temporary 是临时抽屉,persistent 在关闭前保持打开。 |
| ModalProps 属性 | ModalProps={{ backdropProps: {} }} | 传递属性给底层 Modal 组件。 | <Drawer ModalProps={{ keepMounted: true }}>内容</Drawer> | 用于自定义模态对话框的行为。 |
| PaperProps 属性 | PaperProps={{ sx: {} }} | 传递属性给抽屉的 Paper 组件。 | <Drawer PaperProps={{ sx: { width: 240 } }}>自定义宽度</Drawer> | 用于自定义抽屉纸张的样式。 |
| List 组件 | <List></List> | 在抽屉中创建导航列表。 | <Drawer><List><ListItem>项目1</ListItem></List></Drawer> | 提供标准化的列表布局和交互。 |
6.3 底部导航(BottomNavigation)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| BottomNavigation 组件 | <BottomNavigation></BottomNavigation> | 创建底部导航栏,用于移动端的主要导航。 | <BottomNavigation value={value} onChange={handleChange}>导航项</BottomNavigation> | 专为移动设备设计,通常在屏幕底部。 |
| value 属性 | value={currentValue} | 设置当前选中的导航项的值。 | const [value, setValue] = useState(0); <BottomNavigation value={value}> | 必须配合 onChange 实现受控组件。 |
| onChange 事件 | onChange={(event, newValue) => {}} | 处理导航项变化事件。 | const handleChange = (event, newValue) => { setValue(newValue); }; | newValue 是点击的导航项的值。 |
| showLabels 属性 | showLabels={true | false} | 控制是否始终显示标签(而非仅在激活时显示)。 | <BottomNavigation showLabels>始终显示标签</BottomNavigation> | 默认仅在激活项显示标签。 |
| BottomNavigationAction 组件 | <BottomNavigationAction label="标签" icon={<Icon />} /> | 创建底部导航中的单个导航项。 | <BottomNavigationAction label="首页" icon={<HomeIcon />} /> | 需要提供 label 和 icon 属性。 |
| icon 属性 | icon={<IconComponent />} | 设置导航项的图标。 | <BottomNavigationAction icon={<FavoriteIcon />} /> | 可以使用任何 Material-UI 图标组件。 |
| label 属性 | label="导航标签" | 设置导航项的文本标签。 | <BottomNavigationAction label="收藏" /> | 标签会在激活时显示,或当 showLabels 为 true 时始终显示。 |
| sx 属性 | sx={{ custom styles }} | 应用自定义样式到底部导航。 | <BottomNavigation sx={{ bgcolor: 'primary.main' }}>自定义背景</BottomNavigation> | 支持所有系统属性和主题变量。 |
6.4 面包屑(Breadcrumbs)
| 方法/属性名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Breadcrumbs 组件 | <Breadcrumbs></Breadcrumbs> | 创建面包屑导航,显示当前页面在网站结构中的位置。 | <Breadcrumbs><Link href="/">首页</Link><Link href="/products">产品</Link><Typography>当前</Typography></Breadcrumbs> | 自动在面包屑项之间添加分隔符。 |
| separator 属性 | separator=">" | 自定义面包屑项之间的分隔符。 | <Breadcrumbs separator=">"><Link>首页</Link><Link>产品</Link></Breadcrumbs> | 默认分隔符是 /,可以是字符串或 React 元素。 |
| maxItems 属性 | maxItems={number} | 设置最多显示的面包屑项数,超出部分会被折叠。 | <Breadcrumbs maxItems={2}><Link>1</Link><Link>2</Link><Link>3</Link></Breadcrumbs> | 超出项会被折叠为省略号,点击可展开。 |
| itemsAfterCollapse | itemsAfterCollapse={number} | 设置折叠后显示在省略号后面的项数。 | <Breadcrumbs maxItems={3} itemsAfterCollapse={2}>1, 2, 3, 4</Breadcrumbs> | 与 maxItems 配合使用,控制折叠行为。 |
| itemsBeforeCollapse | itemsBeforeCollapse={number} | 设置折叠后显示在省略号前面的项数。 | <Breadcrumbs maxItems={3} itemsBeforeCollapse={1}>1, 2, 3, 4</Breadcrumbs> | 通常设置为 1,显示第一项和最后几项。 |
| Link 组件 | <Link href="url"></Link> | 创建可点击的面包屑链接。 | <Breadcrumbs><Link href="/">首页</Link><Link href="/about">关于</Link></Breadcrumbs> | 用于非当前页面的面包屑项。 |
| Typography 组件 | <Typography color="text.primary"></Typography> | 创建当前页面的面包屑项(不可点击)。 | <Breadcrumbs><Link>首页</Link><Typography color="text.primary">当前</Typography></Breadcrumbs> | 当前页面通常使用 Typography 而非 Link。 |
| sx 属性 | sx={{ custom styles }} | 应用自定义样式到面包屑组件。 | <Breadcrumbs sx={{ fontSize: '14px' }}>自定义样式</Breadcrumbs> | 支持所有系统属性和主题变量。 |
第七章:数据展示组件
7.1 卡片(Card)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Card | <Card>{content}</Card> | 创建卡片容器,承载相关内容。 | <Card><div>卡片内容</div></Card> | 需要配合其他 Card 子组件使用。 |
| CardHeader | <CardHeader title="标题" subheader="副标题" /> | 卡片头部区域,显示标题和副标题。 | <CardHeader title="我的卡片" subheader="这是一个副标题" avatar={<Avatar>M</Avatar>} /> | 可以包含 avatar、action 等属性。 |
| CardMedia | <CardMedia component="img" height="140" image="url" /> | 显示卡片中的媒体内容(图片、视频等)。 | <CardMedia component="img" height="140" image="/static/image.jpg" alt="图片描述" /> | 需要指定 component 属性,常用 img 或 video。 |
| CardContent | <CardContent>{content}</CardContent> | 卡片主要内容区域。 | <CardContent><Typography>这是卡片的主要内容</Typography></CardContent> | 通常包含文本内容。 |
| CardActions | <CardActions>{actions}</CardActions> | 卡片操作按钮区域。 | <CardActions><Button>分享</Button><Button>了解更多</Button></CardActions> | 放置按钮等交互元素。 |
7.2 列表(List)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| List | <List>{listItems}</List> | 列表容器组件。 | <List><ListItem>项目1</ListItem></List> | 需要包含 ListItem 作为子元素。 |
| ListItem | <ListItem>{content}</ListItem> | 单个列表项。 | <ListItem><ListItemText primary="主要文本" secondary="次要文本" /></ListItem> | 可以包含多种子组件。 |
| ListItemText | <ListItemText primary="主文本" secondary="副文本" /> | 列表项中的文本内容。 | <ListItemText primary="标题" secondary="描述信息" /> | primary 和 secondary 都是可选的。 |
| ListItemIcon | <ListItemIcon>{icon}</ListItemIcon> | 列表项中的图标。 | <ListItemIcon><HomeIcon /></ListItemIcon> | 通常放在 ListItemText 之前。 |
| ListItemButton | <ListItemButton>{content}</ListItemButton> | 可点击的列表项。 | <ListItemButton onClick={handleClick}><ListItemText primary="可点击项" /></ListItemButton> | 提供交互功能,替代 div。 |
| ListItemAvatar | <ListItemAvatar>{avatar}</ListItemAvatar> | 列表项中的头像。 | <ListItemAvatar><Avatar src="/avatar.jpg" /></ListItemAvatar> | 专门用于显示头像内容。 |
7.3 表格(Table)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Table | <Table>{tableContent}</Table> | 表格容器组件。 | <Table><TableHead>...</TableHead></Table> | 需要配合其他表格子组件使用。 |
| TableHead | <TableHead>{headerRows}</TableHead> | 表格头部区域。 | <TableHead><TableRow>...</TableRow></TableHead> | 包含表头行和列标题。 |
| TableBody | <TableBody>{bodyRows}</TableBody> | 表格主体区域。 | <TableBody>{rows.map(row => <TableRow>...</TableRow>)}</TableBody> | 包含数据行。 |
| TableRow | <TableRow>{cells}</TableRow> | 表格行。 | <TableRow><TableCell>数据1</TableCell></TableRow> | 可以用于表头或数据行。 |
| TableCell | <TableCell>{content}</TableCell> | 表格单元格。 | <TableCell align="right">数值</TableCell> | 支持对齐方式和大小设置。 |
| TableFooter | <TableFooter>{footerRows}</TableFooter> | 表格底部区域。 | <TableFooter><TableRow>...</TableRow></TableFooter> | 用于显示汇总信息等。 |
| TablePagination | <TablePagination count={100} page={0} rowsPerPage={10} onPageChange={handleChange} /> | 表格分页组件。 | <TablePagination count={100} page={page} rowsPerPage={rowsPerPage} onPageChange={handleChangePage} /> | 需要手动处理分页逻辑。 |
7.4 对话框(Dialog)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Dialog | <Dialog open={open} onClose={handleClose}>{content}</Dialog> | 对话框容器。 | <Dialog open={open} onClose={handleClose}><DialogTitle>标题</DialogTitle></Dialog> | 需要控制 open 状态。 |
| DialogTitle | <DialogTitle>{title}</DialogTitle> | 对话框标题。 | <DialogTitle>确认操作</DialogTitle> | 显示在对话框顶部。 |
| DialogContent | <DialogContent>{content}</DialogContent> | 对话框主要内容。 | <DialogContent><Typography>对话框内容</Typography></DialogContent> | 包含对话框的主体内容。 |
| DialogContentText | <DialogContentText>{text}</DialogContentText> | 对话框中的文本内容。 | <DialogContentText>这是一段描述文本</DialogContentText> | 专门用于文本内容显示。 |
| DialogActions | <DialogActions>{actions}</DialogActions> | 对话框操作按钮区域。 | <DialogActions><Button>取消</Button><Button>确认</Button></DialogActions> | 通常包含确认、取消等按钮。 |
| Dialog fullWidth | <Dialog fullWidth maxWidth="sm">{content}</Dialog> | 全宽对话框。 | <Dialog fullWidth maxWidth="md" open={open}><DialogContent>内容</DialogContent></Dialog> | maxWidth 可设置 xs、sm、md、lg、xl。 |
第八章:反馈组件
8.1 进度条(Progress)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| CircularProgress | <CircularProgress /> | 圆形进度条。 | <CircularProgress /> 或 <CircularProgress value={75} variant="determinate" /> | 默认不确定进度,可设置为确定进度。 |
| LinearProgress | <LinearProgress /> | 线性进度条。 | <LinearProgress /> 或 <LinearProgress value={50} variant="determinate" /> | 适合显示页面或操作进度。 |
| Progress variant | variant="indeterminate" | "determinate" | 进度条变体。 | <CircularProgress variant="determinate" value={75} /> | indeterminate 表示未知进度,determinate 表示已知进度。 |
| Progress color | color="primary" | "secondary" | "inherit" | 进度条颜色。 | <CircularProgress color="secondary" /> | 支持主题色或继承色。 |
| Progress size | size={number | string} | 圆形进度条尺寸。 | <CircularProgress size={40} /> | 数字表示像素值,字符串如 "2rem"。 |
| Progress thickness | thickness={number} | 圆形进度条厚度。 | <CircularProgress thickness={4.5} /> | 控制进度条线条的粗细。 |
8.2 警告(Alert)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Alert | <Alert severity="error">消息</Alert> | 显示警告消息。 | <Alert severity="success">操作成功!</Alert> | 必须指定 severity 属性。 |
| Alert severity | severity="error" | "warning" | "info" | "success" | 警告严重程度。 | <Alert severity="warning">警告信息</Alert> | 不同 severity 对应不同颜色和图标。 |
| Alert variant | variant="standard" | "filled" | "outlined" | 警告变体样式。 | <Alert variant="outlined" severity="info">信息</Alert> | filled 为填充背景,outlined 为边框样式。 |
| Alert action | action={actionElement} | 警告操作按钮。 | <Alert action={<Button>撤销</Button>}>消息</Alert> | 在警告右侧添加操作按钮。 |
| Alert onClose | onClose={handleClose} | 关闭回调函数。 | <Alert onClose={() => setOpen(false)}>可关闭的警告</Alert> | 会自动显示关闭图标。 |
| Alert icon | icon={iconElement} | 自定义图标。 | <Alert icon={<CheckIcon />}>自定义图标</Alert> | 可覆盖默认的 severity 图标。 |
8.3 提示(Snackbar)
| 组件名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| Snackbar | <Snackbar open={open} message="提示消息" /> | 底部提示组件。 | <Snackbar open={open} autoHideDuration={6000} onClose={handleClose} message="操作成功" /> | 需要控制 open 状态。 |
| Snackbar autoHideDuration | autoHideDuration={number} | 自动隐藏时间。 | <Snackbar autoHideDuration={3000} message="3秒后消失" /> | 单位为毫秒,null 表示不自动隐藏。 |
| Snackbar anchorOrigin | anchorOrigin={{ vertical, horizontal }} | 提示位置。 | <Snackbar anchorOrigin={{ vertical: 'top', horizontal: 'center' }} message="顶部居中" /> | vertical: top/bottom, horizontal: left/center/right。 |
| Snackbar action | action={actionElement} | 提示操作按钮。 | <Snackbar action={<Button>撤销</Button>} message="操作完成" /> | 在提示右侧添加操作按钮。 |
| Snackbar onClose | onClose={handleClose} | 关闭回调函数。 | <Snackbar open={open} onClose={handleClose} message="提示" /> | 点击其他地方或超时都会触发。 |
| SnackbarContent | <SnackbarContent message="消息" action={action} /> | 提示内容组件。 | <SnackbarContent message={<span>自定义消息</span>} action={<Button>操作</Button>} /> | 可单独使用,不包含自动隐藏逻辑。 |
第九章:高级主题
9.1 自定义主题
| 方法/概念名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| createTheme | createTheme(options) | 创建自定义主题。 | const theme = createTheme({ palette: { primary: { main: '#1976d2' } } }); | 返回一个主题对象,需要传递给 ThemeProvider。 |
| ThemeProvider | <ThemeProvider theme={theme}>{children}</ThemeProvider> | 提供主题给组件树。 | <ThemeProvider theme={theme}><App /></ThemeProvider> | 需要在应用顶层使用。 |
| palette | palette: { primary, secondary, error, warning, info, success } | 定义调色板颜色。 | palette: { primary: { main: '#1976d2', light: '#42a5f5', dark: '#1565c0' } } | 至少需要定义 primary 和 secondary。 |
| typography | typography: { fontFamily, h1, h2, body1, button } | 定义字体样式。 | typography: { fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', h1: { fontSize: '2rem' } } | 可以自定义所有文本变体。 |
| spacing | spacing: number | function | 定义间距单位。 | spacing: 8 或 spacing: (factor) => \${0.5 * factor}rem“ | 默认为 8px 倍数,可自定义函数。 |
| breakpoints | breakpoints: { values: { xs, sm, md, lg, xl } } | 定义响应式断点。 | breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536 } } | 值单位为 px。 |
| useTheme | const theme = useTheme() | 在组件中访问主题对象。 | const theme = useTheme(); const primaryColor = theme.palette.primary.main; | 只能在函数组件中使用。 |
| responsiveFontSizes | responsiveFontSizes(theme) | 使字体大小响应式。 | const theme = responsiveFontSizes(createTheme()); | 需要传入主题对象,返回新主题。 |
9.2 性能优化
| 方法/概念名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| memo | React.memo(Component) | 防止不必要的重新渲染。 | const MyComponent = React.memo(function MyComponent(props) { return <div>{props.value}</div>; }); | 浅比较 props,复杂对象可能需要自定义比较函数。 |
| useMemo | const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); | 缓存昂贵的计算结果。 | const expensiveValue = useMemo(() => computeValue(props.data), [props.data]); | 依赖数组变化时才会重新计算。 |
| useCallback | const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); | 缓存回调函数。 | const handleClick = useCallback(() => { setCount(count + 1); }, [count]); | 避免子组件因回调函数重新创建而不必要的重渲染。 |
| lazy | const Component = lazy(() => import('./Component')); | 组件懒加载。 | const LazyComponent = lazy(() => import('./LazyComponent')); | 需要与 Suspense 配合使用。 |
| Suspense | <Suspense fallback={<div>Loading...</div>}><LazyComponent /></Suspense> | 懒加载时的降级 UI。 | <Suspense fallback={<CircularProgress />}><LazyComponent /></Suspense> | 提供加载中的备用内容。 |
| shouldComponentUpdate | shouldComponentUpdate(nextProps, nextState) | 类组件中控制更新。 | shouldComponentUpdate(nextProps) { return this.props.value !== nextProps.value; } | 仅适用于类组件,函数组件使用 React.memo。 |
| virtualization | 使用虚拟化列表 | 优化长列表性能。 | import { FixedSizeList as List } from 'react-window'; <List height={400} itemCount={1000} itemSize={35}>{Row}</List> | 只渲染可见区域的元素,大幅提升性能。 |
9.3 与 React 库集成
| 方法/概念名称 | 语法 | 用途 | 代码示例 | 注意事项 |
|---|---|---|---|---|
| React Router Link | <Link to="/path">Link</Link> | 与 React Router 集成导航。 | <Button component={Link} to="/home">首页</Button> | 需要安装 react-router-dom。 |
| styled-components | styled(Component)(styles) | 与 styled-components 集成。 | const StyledButton = styled(Button)\ background: linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%); `;` | 需要安装 styled-components。 |
| Formik 集成 | <Formik>{({ values, handleChange }) => (<TextField name="email" value={values.email} onChange={handleChange} />)}</Formik> | 与 Formik 表单库集成。 | <Field as={TextField} name="email" label="Email" variant="outlined" /> | 需要安装 formik。 |
| React Hook Form | useForm() | 与 React Hook Form 集成。 | const { register, handleSubmit } = useForm(); <TextField {...register('firstName')} /> | 需要安装 react-hook-form。 |
| Redux 集成 | useSelector, useDispatch | 与 Redux 状态管理集成。 | const count = useSelector(state => state.count); const dispatch = useDispatch(); <Button onClick={() => dispatch(increment())}>+</Button> | 需要安装 react-redux。 |
| React Query | useQuery, useMutation | 与 React Query 数据获取集成。 | const { data, isLoading } = useQuery('todos', fetchTodos); {isLoading ? <CircularProgress /> : <div>{data}</div>} | 需要安装 react-query。 |
| Framer Motion | motion(Component) | 与 Framer Motion 动画库集成。 | const MotionButton = motion(Button); <MotionButton whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} /> | 需要安装 framer-motion。 |