1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
import React, { useState } from 'react';
// 引入 MUI 核心组件
import {
Button, Card, CardContent, Container,
TextField, Typography, Box, ThemeProvider,
createTheme, Grid, Alert
} from '@mui/material';
// 引入 MUI 图标
import AddCircleIcon from '@mui/icons-material/AddCircle';
import '@fontsource/roboto/300.css';
import '@fontsource/roboto/400.css';
import '@fontsource/roboto/500.css';
import '@fontsource/roboto/700.css';
// 1. 自定义主题(覆盖默认颜色)
const customTheme = createTheme({
palette: {
primary: {
main: '#1976d2', // 主色调
},
secondary: {
main: '#dc004e', // 次要色调
},
},
typography: {
fontFamily: 'Roboto, sans-serif', // 字体
},
});
function App() {
// 2. 状态管理(表单输入)
const [inputValue, setInputValue] = useState('');
const [showAlert, setShowAlert] = useState(false);
// 3. 按钮点击事件
const handleSubmit = () => {
if (inputValue) {
setShowAlert(true);
setTimeout(() => setShowAlert(false), 3000);
}
};
return (
// 4. 应用自定义主题
<ThemeProvider theme={customTheme}>
{/* 容器:居中 + 内边距 */}
<Container maxWidth="sm" sx={{ mt: 4, mb: 4 }}>
{/* 标题 */}
<Typography variant="h4" align="center" gutterBottom>
MUI 基础案例
</Typography>
{/* 卡片组件 */}
<Card sx={{ mb: 3 }}>
<CardContent>
{/* 网格布局:一行两列 */}
<Grid container spacing={2} alignItems="center">
<Grid item xs={8}>
{/* 文本输入框 */}
<TextField
label="输入内容"
variant="outlined"
fullWidth
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="请输入任意内容"
/>
</Grid>
<Grid item xs={4}>
{/* 按钮(带图标) */}
<Button
variant="contained" // 填充样式
color="primary" // 主色调
fullWidth
startIcon={<AddCircleIcon />} // 左侧图标
onClick={handleSubmit}
>
提交
</Button>
</Grid>
</Grid>
</CardContent>
</Card>
{/* 提示框(条件显示) */}
{showAlert && (
<Alert severity="success" sx={{ mb: 2 }}>
提交成功!你输入的内容是:{inputValue}
</Alert>
)}
{/* 不同样式的按钮示例 */}
<Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
<Button variant="outlined" color="secondary">
轮廓按钮
</Button>
<Button variant="text">文本按钮</Button>
<Button disabled>禁用按钮</Button>
</Box>
</Container>
</ThemeProvider>
);
}
export default App;
|