Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

UI 组件库

MUI 示例:局部字段、进度边界与选项卡

切换可见状态; 限制缓冲值; 选择页签内容.

案例

这个案例集合中的条目

代码tsx简单

Material-UI 基础

基础Material-UI组件,包括按钮、卡片、表单和基本Material Design元素

难度

3/10

预计时间

30 min

标签

react, typescript, material design, ui components

前置条件

React basics, TypeScript, Material Design principles

tsx
// Material-UI (MUI) Fundamentals Examples
// Install required packages:
// npm install @mui/material @emotion/react @emotion/styled @mui/icons-material @mui/lab

import React from 'react';
import {
  Box,
  Button,
  Card,
  CardActions,
  CardContent,
  CardHeader,
  CardMedia,
  Container,
  CssBaseline,
  Divider,
  Grid,
  IconButton,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Stack,
  TextField,
  Typography,
  Avatar,
  Badge,
  Chip,
  Rating,
  Switch,
  Slider,
  LinearProgress,
  CircularProgress,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Alert,
  AlertTitle,
  Skeleton,
  Paper,
  InputAdornment,
  FormControl,
  InputLabel,
  OutlinedInput,
  Checkbox,
  FormControlLabel,
  Select,
  MenuItem,
  FormHelperText,
  Tabs,
  Tab,
} from '@mui/material';
import {
  Search,
  AccountCircle,
  Mail,
  Visibility,
  VisibilityOff,
  ExpandMore,
  Favorite,
  Share,
  MoreVert,
  Send,
  CloudUpload,
  Download,
  Settings,
  Dashboard,
  People,
  Assessment,
} from '@mui/icons-material';

// 1. Button Examples
export function ButtonExamples() {
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Material Design Buttons
      </Typography>

      {/* Button Variants */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Button Variants
        </Typography>
        <Stack spacing={2} direction="row" alignItems="center">
          <Button variant="text">Text</Button>
          <Button variant="outlined">Outlined</Button>
          <Button variant="contained">Contained</Button>
          <Button variant="contained" disableElevation>
            No Elevation
          </Button>
        </Stack>
      </Box>

      {/* Button Colors */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Button Colors
        </Typography>
        <Stack spacing={2} direction="row">
          <Button color="primary">Primary</Button>
          <Button color="secondary">Secondary</Button>
          <Button color="success">Success</Button>
          <Button color="error">Error</Button>
          <Button color="info">Info</Button>
          <Button color="warning">Warning</Button>
        </Stack>
      </Box>

      {/* Button Sizes */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Button Sizes
        </Typography>
        <Stack spacing={2} direction="row" alignItems="center">
          <Button size="small">Small</Button>
          <Button size="medium">Medium</Button>
          <Button size="large">Large</Button>
        </Stack>
      </Box>

      {/* Button with Icons */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Buttons with Icons
        </Typography>
        <Stack spacing={2} direction="row">
          <Button startIcon={<Send />}>Send</Button>
          <Button endIcon={<CloudUpload />}>Upload</Button>
          <IconButton color="primary">
            <Favorite />
          </IconButton>
          <IconButton color="secondary">
            <MoreVert />
          </IconButton>
        </Stack>
      </Box>

      {/* Button States */}
      <Box>
        <Typography variant="h6" gutterBottom>
          Button States
        </Typography>
        <Stack spacing={2} direction="row">
          <Button disabled>Disabled</Button>
          <Button loading variant="contained">
            Loading
          </Button>
          <Button variant="contained" href="#contained-buttons">
            Link
          </Button>
        </Stack>
      </Box>
    </Box>
  );
}

// 2. Card Examples
export function CardExamples() {
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Material Design Cards
      </Typography>

      <Grid container spacing={3}>
        {/* Basic Card */}
        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography variant="h5" component="div">
                Basic Card
              </Typography>
              <Typography variant="body2" color="text.secondary">
                This is a basic Material Design card with content area and optional actions.
              </Typography>
            </CardContent>
            <CardActions>
              <Button size="small">Learn More</Button>
              <Button size="small">Share</Button>
            </CardActions>
          </Card>
        </Grid>

        {/* Media Card */}
        <Grid item xs={12} sm={6} md={4}>
          <Card sx={{ maxWidth: 345 }}>
            <CardMedia
              component="img"
              height="140"
              image="https://images.unsplash.com/photo-1551963831-b3b1ca40c98e"
              alt="Live from space album cover"
            />
            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                Media Card
              </Typography>
              <Typography variant="body2" color="text.secondary">
                This card demonstrates the use of CardMedia component to display images.
              </Typography>
            </CardContent>
            <CardActions>
              <Button size="small">Share</Button>
              <Button size="small">Learn More</Button>
            </CardActions>
          </Card>
        </Grid>

        {/* Interactive Card */}
        <Grid item xs={12} sm={6} md={4}>
          <Card sx={{ maxWidth: 345 }}>
            <CardHeader
              avatar={
                <Avatar sx={{ bgcolor: 'red[500]' }} aria-label="recipe">
                  R
                </Avatar>
              }
              action={
                <IconButton aria-label="settings">
                  <Settings />
                </IconButton>
              }
              title="Interactive Card"
              subheader="September 14, 2023"
            />
            <CardContent>
              <Typography variant="body2" color="text.secondary">
                This impressive paella is a perfect party dish and a fun meal to cook together with your guests.
              </Typography>
            </CardContent>
            <CardActions disableSpacing>
              <IconButton aria-label="add to favorites">
                <Favorite />
              </IconButton>
              <IconButton aria-label="share">
                <Share />
              </IconButton>
            </CardActions>
          </Card>
        </Grid>

        {/* Stats Card */}
        <Grid item xs={12} sm={6} md={4}>
          <Paper sx={{ p: 2, textAlign: 'center' }}>
            <Typography variant="h4" color="primary" gutterBottom>
              2,350
            </Typography>
            <Typography variant="h6" color="text.secondary">
              Total Users
            </Typography>
            <Typography variant="body2" color="success.main">
              +12.5% from last month
            </Typography>
          </Paper>
        </Grid>

        {/* Chart Card */}
        <Grid item xs={12} sm={6} md={4}>
          <Card>
            <CardContent>
              <Typography variant="h5" component="div" gutterBottom>
                Performance
              </Typography>
              <LinearProgress
                variant="determinate"
                value={75}
                sx={{ mb: 2 }}
              />
              <Typography variant="body2" color="text.secondary">
                CPU Usage: 75%
              </Typography>
              <LinearProgress
                variant="determinate"
                value={45}
                color="secondary"
                sx={{ mb: 2, mt: 2 }}
              />
              <Typography variant="body2" color="text.secondary">
                Memory Usage: 45%
              </Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* Action Card */}
        <Grid item xs={12} sm={6} md={4}>
          <Card sx={{ backgroundColor: 'primary.main', color: 'white' }}>
            <CardContent>
              <Typography variant="h5" component="div" gutterBottom>
                Upgrade Plan
              </Typography>
              <Typography variant="body2" sx={{ mb: 2 }}>
                Unlock premium features with our Pro plan
              </Typography>
              <Button variant="contained" color="secondary">
                Upgrade Now
              </Button>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
}

// 3. Form Examples
export function FormExamples() {
  const [values, setValues] = React.useState({
    amount: '',
    password: '',
    weight: '',
    weightRange: '',
    showPassword: false,
  });

  const handleChange = (prop: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setValues({ ...values, [prop]: event.target.value });
  };

  const handleClickShowPassword = () => {
    setValues({
      ...values,
      showPassword: !values.showPassword,
    });
  };

  const handleMouseDownPassword = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
  };

  return (
    <Box sx={{ p: 3, maxWidth: 600, mx: 'auto' }}>
      <Typography variant="h5" gutterBottom>
        Material Design Forms
      </Typography>

      <Paper sx={{ p: 3 }}>
        <Stack spacing={3}>
          {/* Text Field Variants */}
          <Typography variant="h6" gutterBottom>
            Text Field Variants
          </Typography>
          <TextField label="Outlined" variant="outlined" />
          <TextField label="Filled" variant="filled" />
          <TextField label="Standard" variant="standard" />

          {/* Text Fields with Icons */}
          <Typography variant="h6" gutterBottom sx={{ mt: 3 }}>
            Text Fields with Icons
          </Typography>
          <TextField
            label="With Start Adornment"
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <AccountCircle />
                </InputAdornment>
              ),
            }}
          />
          <TextField
            label="With End Adornment"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <Search />
                </InputAdornment>
              ),
            }}
          />

          {/* Password Field */}
          <Typography variant="h6" gutterBottom sx={{ mt: 3 }}>
            Password Field
          </Typography>
          <FormControl variant="outlined">
            <InputLabel htmlFor="outlined-adornment-password">
              Password
            </InputLabel>
            <OutlinedInput
              id="outlined-adornment-password"
              type={values.showPassword ? 'text' : 'password'}
              value={values.password}
              onChange={handleChange('password')}
              endAdornment={
                <InputAdornment position="end">
                  <IconButton
                    aria-label="toggle password visibility"
                    onClick={handleClickShowPassword}
                    onMouseDown={handleMouseDownPassword}
                    edge="end"
                  >
                    {values.showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              }
              label="Password"
            />
          </FormControl>

          {/* Select Field */}
          <Typography variant="h6" gutterBottom sx={{ mt: 3 }}>
            Select Field
          </Typography>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">Age</InputLabel>
            <Select
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              label="Age"
            >
              <MenuItem value={10}>Ten</MenuItem>
              <MenuItem value={20}>Twenty</MenuItem>
              <MenuItem value={30}>Thirty</MenuItem>
            </Select>
          </FormControl>

          {/* Checkbox and Switch */}
          <Typography variant="h6" gutterBottom sx={{ mt: 3 }}>
            Controls
          </Typography>
          <Stack direction="row" spacing={2}>
            <FormControlLabel
              control={<Checkbox defaultChecked />}
              label="Remember me"
            />
            <FormControlLabel control={<Switch />} label="Enable notifications" />
          </Stack>

          {/* Submit Button */}
          <Box sx={{ mt: 3 }}>
            <Button variant="contained" fullWidth>
              Submit Form
            </Button>
          </Box>
        </Stack>
      </Paper>
    </Box>
  );
}

// 4. Badge and Chip Examples
export function BadgeChipExamples() {
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Badges & Chips
      </Typography>

      {/* Badges */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Badges
        </Typography>
        <Stack spacing={2} direction="row" alignItems="center">
          <Badge badgeContent={4} color="primary">
            <Mail color="action" />
          </Badge>
          <Badge badgeContent={100} color="secondary" max={99}>
            <Mail color="action" />
          </Badge>
          <Badge color="error" variant="dot">
            <Mail color="action" />
          </Badge>
          <Badge badgeContent={0} showZero color="info">
            <Mail color="action" />
          </Badge>
        </Stack>
      </Box>

      {/* Chips */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Chips
        </Typography>
        <Stack direction="row" spacing={1}>
          <Chip label="Basic" />
          <Chip label="Clickable" onClick={() => {}} />
          <Chip label="Deletable" onDelete={() => {}} />
          <Chip label="Primary" color="primary" />
          <Chip label="Secondary" color="secondary" />
          <Chip
            avatar={<Avatar>MB</Avatar>}
            label="Avatar"
          />
          <Chip
            icon={<CloudUpload />}
            label="With Icon"
          />
        </Stack>
      </Box>

      {/* Chip Variants */}
      <Box>
        <Typography variant="h6" gutterBottom>
          Chip Variants
        </Typography>
        <Stack spacing={2}>
          <Stack direction="row" spacing={1}>
            <Chip label="Outlined" variant="outlined" />
            <Chip label="Outlined Primary" variant="outlined" color="primary" />
            <Chip label="Outlined Secondary" variant="outlined" color="secondary" />
          </Stack>
          <Stack direction="row" spacing={1}>
            <Chip label="Filled" variant="filled" />
            <Chip label="Filled Primary" variant="filled" color="primary" />
            <Chip label="Filled Secondary" variant="filled" color="secondary" />
          </Stack>
        </Stack>
      </Box>
    </Box>
  );
}

// 5. Avatar Examples
export function AvatarExamples() {
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Avatars
      </Typography>

      {/* Avatar Sizes */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Avatar Sizes
        </Typography>
        <Stack direction="row" spacing={2} alignItems="center">
          <Avatar sx={{ width: 24, height: 24 }} />
          <Avatar sx={{ width: 32, height: 32 }} />
          <Avatar sx={{ width: 40, height: 40 }} />
          <Avatar sx={{ width: 56, height: 56 }} />
          <Avatar sx={{ width: 64, height: 64 }} />
        </Stack>
      </Box>

      {/* Avatar Variants */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Avatar Variants
        </Typography>
        <Stack direction="row" spacing={2}>
          <Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" />
          <Avatar>H</Avatar>
          <Avatar sx={{ bgcolor: 'primary.main' }}>N</Avatar>
          <Avatar sx={{ bgcolor: 'secondary.main' }}>OP</Avatar>
        </Stack>
      </Box>

      {/* Avatar with Badge */}
      <Box>
        <Typography variant="h6" gutterBottom>
          Avatar with Badge
        </Typography>
        <Stack direction="row" spacing={2}>
          <Badge
            overlap="circular"
            anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
            badgeContent={
              <Avatar
                sx={{ width: 24, height: 24, border: '2px solid white' }}
                src="/static/images/avatar/2.jpg"
              />
            }
          >
            <Avatar sx={{ width: 56, height: 56 }} src="/static/images/avatar/1.jpg" />
          </Badge>
          <Badge
            overlap="circular"
            anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
            variant="dot"
          >
            <Avatar sx={{ width: 56, height: 56 }} src="/static/images/avatar/3.jpg" />
          </Badge>
        </Stack>
      </Box>
    </Box>
  );
}

// 6. Progress Examples
export function ProgressExamples() {
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    const timer = setInterval(() => {
      setProgress((prevProgress) => (prevProgress >= 100 ? 0 : prevProgress + 10));
    }, 800);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Progress Indicators
      </Typography>

      {/* Linear Progress */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          Linear Progress
        </Typography>
        <Box sx={{ mb: 2 }}>
          <LinearProgress />
        </Box>
        <Box sx={{ mb: 2 }}>
          <LinearProgress color="secondary" />
        </Box>
        <Box sx={{ mb: 2 }}>
          <LinearProgress variant="determinate" value={progress} />
        </Box>
        <Box>
          <LinearProgress variant="buffer" value={progress} valueBuffer={Math.min(100, progress + 10)} />
        </Box>
      </Box>

      {/* Circular Progress */}
      <Box>
        <Typography variant="h6" gutterBottom>
          Circular Progress
        </Typography>
        <Stack direction="row" spacing={2}>
          <CircularProgress />
          <CircularProgress color="secondary" />
          <CircularProgress variant="determinate" value={25} />
          <CircularProgress variant="determinate" value={50} />
          <CircularProgress variant="determinate" value={75} />
          <CircularProgress variant="determinate" value={100} />
        </Stack>
      </Box>
    </Box>
  );
}

// 7. List Examples
export function ListExamples() {
  const [dense, setDense] = React.useState(false);
  const [secondary, setSecondary] = React.useState(false);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Lists
      </Typography>

      <Stack spacing={2} sx={{ mb: 4 }}>
        <FormControlLabel
          control={
            <Checkbox
              checked={dense}
              onChange={(event) => setDense(event.target.checked)}
            />
          }
          label="Enable dense"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={secondary}
              onChange={(event) => setSecondary(event.target.checked)}
            />
          }
          label="Enable secondary text"
        />
      </Stack>

      <List dense={dense}>
        <ListItem>
          <ListItemIcon>
            <Dashboard />
          </ListItemIcon>
          <ListItemText
            primary="Dashboard"
            secondary={secondary ? 'View your dashboard and analytics' : null}
          />
        </ListItem>
        <ListItem>
          <ListItemIcon>
            <People />
          </ListItemIcon>
          <ListItemText
            primary="Users"
            secondary={secondary ? 'Manage users and permissions' : null}
          />
        </ListItem>
        <ListItem>
          <ListItemIcon>
            <Assessment />
          </ListItemIcon>
          <ListItemText
            primary="Reports"
            secondary={secondary ? 'Generate and view reports' : null}
          />
        </ListItem>
      </List>
    </Box>
  );
}

// 8. Accordion Examples
export function AccordionExamples() {
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Accordion
      </Typography>

      <Box sx={{ maxWidth: 600, mx: 'auto' }}>
        <Accordion>
          <AccordionSummary
            expandIcon={<ExpandMore />}
            aria-controls="panel1a-content"
            id="panel1a-header"
          >
            <Typography>Accordion 1</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Typography>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
              malesuada lacus ex, sit amet blandit leo lobortis eget.
            </Typography>
          </AccordionDetails>
        </Accordion>
        <Accordion>
          <AccordionSummary
            expandIcon={<ExpandMore />}
            aria-controls="panel2a-content"
            id="panel2a-header"
          >
            <Typography>Accordion 2</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <Typography>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
              malesuada lacus ex, sit amet blandit leo lobortis eget.
            </Typography>
          </AccordionDetails>
        </Accordion>
        <Accordion disabled>
          <AccordionSummary
            expandIcon={<ExpandMore />}
            aria-controls="panel3a-content"
            id="panel3a-header"
          >
            <Typography>Disabled Accordion</Typography>
          </AccordionSummary>
        </Accordion>
      </Box>
    </Box>
  );
}

// 9. Alert Examples
export function AlertExamples() {
  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Alerts
      </Typography>

      <Stack spacing={2}>
        <Alert severity="success">
          <AlertTitle>Success</AlertTitle>
          This is a success alert — <strong>check it out!</strong>
        </Alert>
        <Alert severity="info">
          <AlertTitle>Info</AlertTitle>
          This is an info alert — <strong>check it out!</strong>
        </Alert>
        <Alert severity="warning">
          <AlertTitle>Warning</AlertTitle>
          This is a warning alert — <strong>check it out!</strong>
        </Alert>
        <Alert severity="error">
          <AlertTitle>Error</AlertTitle>
          This is an error alert — <strong>check it out!</strong>
        </Alert>
      </Stack>
    </Box>
  );
}

// 10. Tabs Example
export function TabExample() {
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: '100%', p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Tabs
      </Typography>
      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
          <Tab label="Item One" />
          <Tab label="Item Two" />
          <Tab label="Item Three" />
        </Tabs>
      </Box>
      <Box sx={{ p: 3 }}>
        {value === 0 && (
          <Typography>
            Item One content. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
          </Typography>
        )}
        {value === 1 && (
          <Typography>
            Item Two content. Suspendisse malesuada lacus ex, sit amet blandit leo lobortis.
          </Typography>
        )}
        {value === 2 && (
          <Typography>
            Item Three content. Phasellus viverra nulla ut metus varius laoreet.
          </Typography>
        )}
      </Box>
    </Box>
  );
}

// Main Showcase Component
export function MaterialUiShowcase() {
  return (
    <Container maxWidth="xl">
      <CssBaseline />
      <Box sx={{ py: 4 }}>
        <Typography variant="h3" component="h1" gutterBottom align="center">
          Material-UI (MUI) Components
        </Typography>
        <Typography variant="h6" color="text.secondary" align="center" sx={{ mb: 6 }}>
          Google Material Design implementation for React
        </Typography>

        <Stack spacing={4}>
          <ButtonExamples />
          <Divider />
          <CardExamples />
          <Divider />
          <FormExamples />
          <Divider />
          <BadgeChipExamples />
          <Divider />
          <AvatarExamples />
          <Divider />
          <ProgressExamples />
          <Divider />
          <ListExamples />
          <Divider />
          <AccordionExamples />
          <Divider />
          <AlertExamples />
          <Divider />
          <TabExample />
        </Stack>
      </Box>
    </Container>
  );
}

export {
  ButtonExamples,
  CardExamples,
  FormExamples,
  BadgeChipExamples,
  AvatarExamples,
  ProgressExamples,
  ListExamples,
  AccordionExamples,
  AlertExamples,
  TabExample,
  MaterialUiShowcase
};
代码tsx中等

高级Material-UI组件

高级Material-UI功能,包括数据网格、日期选择器、主题定制和复杂布局

难度

8/10

预计时间

45 min

标签

react, typescript, advanced, data management, theme

前置条件

Advanced React, Material-UI basics, TypeScript

tsx
// Advanced Material-UI Components Examples
// Install additional packages:
// npm install @mui/x-data-grid @mui/x-date-pickers @mui/lab @emotion/react @emotion/styled

import React, { useState, useCallback, useMemo } from 'react';
import {
  Box,
  Button,
  Container,
  CssBaseline,
  Divider,
  Grid,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Paper,
  Rating,
  Switch,
  TextField,
  Typography,
  useTheme,
  createTheme,
  ThemeProvider,
  AppBar,
  Toolbar,
  Drawer,
  ListSubheader,
  ListItemIcon,
  ListItemButton,
  MenuList,
  MenuItem,
  Menu,
  Fade,
  Popover,
  Modal,
  Backdrop,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Select,
  FormControl,
  InputLabel,
  Chip,
  Avatar,
  Tabs,
  Tab,
  Card,
  CardContent,
  CardHeader,
  CardActions,
  Breadcrumbs,
  Link,
  Stepper,
  Step,
  StepLabel,
  StepContent,
  MobileStepper,
  Pagination,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableSortLabel,
  Skeleton,
  ToggleButton,
  ToggleButtonGroup,
  SpeedDial,
  SpeedDialIcon,
  SpeedDialAction,
  Fab,
  Tooltip,
  Zoom,
  Grow,
  Slide,
} from '@mui/material';
import {
  DataGrid,
  GridColDef,
  GridToolbar,
  GridActionsCellItem,
  GridRowModesModel,
  GridRowEditStopReasons,
  GridRowModes,
  GridToolbarContainer,
  GridToolbarColumnsButton,
  GridToolbarFilterButton,
  GridToolbarDensitySelector,
  GridToolbarExport,
} from '@mui/x-data-grid';
import {
  LocalizationProvider,
  DatePicker,
  DateTimePicker,
  TimePicker,
} from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import {
  Inbox,
  Drafts,
  Send,
  Delete,
  Menu,
  Search,
  Add,
  Edit,
  Save,
  Cancel,
  Settings,
  Share,
  Favorite,
  Home,
  Business,
  Timeline,
  LocalOffer,
  Assessment,
  CloudUpload,
  Download,
  Print,
  FilterList,
} from '@mui/icons-material';

// 1. Custom Theme Configuration
const darkTheme = createTheme({
  palette: {
    mode: 'dark',
    primary: {
      main: '#90caf9',
    },
    secondary: {
      main: '#f48fb1',
    },
    background: {
      default: '#121212',
      paper: '#1e1e1e',
    },
  },
});

const customTheme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
      light: '#42a5f5',
      dark: '#1565c0',
    },
    secondary: {
      main: '#dc004e',
    },
    error: {
      main: '#ff5722',
    },
    warning: {
      main: '#ff9800',
    },
    info: {
      main: '#2196f3',
    },
    success: {
      main: '#4caf50',
    },
  },
  typography: {
    fontFamily: 'Roboto, Arial, sans-serif',
    h1: {
      fontSize: '2.5rem',
      fontWeight: 600,
    },
    h2: {
      fontSize: '2rem',
      fontWeight: 600,
    },
    body1: {
      fontSize: '1rem',
      lineHeight: 1.6,
    },
  },
  shape: {
    borderRadius: 8,
  },
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: 'none',
          borderRadius: 8,
        },
      },
    },
    MuiCard: {
      styleOverrides: {
        root: {
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          borderRadius: 12,
        },
      },
    },
  },
});

// 2. Advanced Data Grid
export function AdvancedDataGrid() {
  const initialRows = [
    { id: 1, name: 'John Doe', email: '[email protected]', age: 35, role: 'Developer', status: 'Active' },
    { id: 2, name: 'Jane Smith', email: '[email protected]', age: 28, role: 'Designer', status: 'Active' },
    { id: 3, name: 'Bob Johnson', email: '[email protected]', age: 42, role: 'Manager', status: 'Inactive' },
    { id: 4, name: 'Alice Brown', email: '[email protected]', age: 31, role: 'Developer', status: 'Active' },
    { id: 5, name: 'Charlie Wilson', email: '[email protected]', age: 39, role: 'Analyst', status: 'Active' },
  ];

  const [rows, setRows] = useState(initialRows);
  const [rowModesModel, setRowModesModel] = useState<GridRowModesModel>({});

  const columns: GridColDef[] = [
    { field: 'name', headerName: 'Name', width: 180, editable: true },
    { field: 'email', headerName: 'Email', width: 200, editable: true },
    { field: 'age', headerName: 'Age', type: 'number', width: 80, editable: true },
    { field: 'role', headerName: 'Role', width: 150, editable: true },
    {
      field: 'status',
      headerName: 'Status',
      width: 120,
      editable: true,
      type: 'singleSelect',
      valueOptions: ['Active', 'Inactive'],
    },
    {
      field: 'actions',
      type: 'actions',
      headerName: 'Actions',
      width: 100,
      cellClassName: 'actions',
      getActions: ({ id }) => {
        const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;

        if (isInEditMode) {
          return [
            <GridActionsCellItem
              icon={<Save />}
              label="Save"
              sx={{ color: 'primary.main' }}
              onClick={() => {}}
            />,
            <GridActionsCellItem
              icon={<Cancel />}
              label="Cancel"
              sx={{ color: 'error.main' }}
              onClick={() => {}}
            />,
          ];
        }

        return [
          <GridActionsCellItem
            icon={<Edit />}
            label="Edit"
            className="textPrimary"
            onClick={() => {}}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<Delete />}
            label="Delete"
            onClick={() => {}}
            color="inherit"
          />,
        ];
      },
    },
  ];

  return (
    <Box sx={{ height: 400, width: '100%', mb: 4 }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        disableSelectionOnClick
        experimentalFeatures={{ newEditingApi: true }}
        editMode="row"
        rowModesModel={rowModesModel}
        slots={{
          toolbar: GridToolbar,
        }}
      />
    </Box>
  );
}

// 3. Date and Time Pickers
export function DateTimePickers() {
  const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());
  const [selectedDateTime, setSelectedDateTime] = useState<Date | null>(new Date());
  const [selectedTime, setSelectedTime] = useState<Date | null>(new Date());

  return (
    <ThemeProvider theme={customTheme}>
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <Box sx={{ p: 3 }}>
          <Typography variant="h5" gutterBottom>
            Date & Time Pickers
          </Typography>

          <Grid container spacing={3}>
            <Grid item xs={12} sm={4}>
              <DatePicker
                label="Date Picker"
                value={selectedDate}
                onChange={(newValue) => setSelectedDate(newValue)}
                renderInput={(params) => <TextField {...params} fullWidth />}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <DateTimePicker
                label="Date Time Picker"
                value={selectedDateTime}
                onChange={(newValue) => setSelectedDateTime(newValue)}
                renderInput={(params) => <TextField {...params} fullWidth />}
              />
            </Grid>
            <Grid item xs={12} sm={4}>
              <TimePicker
                label="Time Picker"
                value={selectedTime}
                onChange={(newValue) => setSelectedTime(newValue)}
                renderInput={(params) => <TextField {...params} fullWidth />}
              />
            </Grid>
          </Grid>
        </Box>
      </LocalizationProvider>
    </ThemeProvider>
  );
}

// 4. App Layout with Navigation
export function AppLayout() {
  const [open, setOpen] = useState(false);

  const handleDrawerToggle = () => {
    setOpen(!open);
  };

  const drawer = (
    <Box>
      <Toolbar />
      <Divider />
      <List>
        {['Dashboard', 'Users', 'Settings', 'Reports'].map((text, index) => (
          <ListItem key={text} disablePadding>
            <ListItemButton>
              <ListItemIcon>
                {index % 2 === 0 ? <Inbox /> : <Mail />}
              </ListItemIcon>
              <ListItemText primary={text} />
            </ListItemButton>
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (
    <ThemeProvider theme={customTheme}>
      <Box sx={{ display: 'flex' }}>
        <CssBaseline />
        <AppBar
          position="fixed"
          sx={{
            width: { sm: `calc(100% - ${240}px)` },
            ml: { sm: `${240}px` },
          }}
        >
          <Toolbar>
            <IconButton
              color="inherit"
              aria-label="open drawer"
              edge="start"
              onClick={handleDrawerToggle}
              sx={{ mr: 2, display: { sm: 'none' } }}
            >
              <Menu />
            </IconButton>
            <Typography variant="h6" noWrap component="div">
              Responsive drawer
            </Typography>
          </Toolbar>
        </AppBar>
        <Box
          component="nav"
          sx={{ width: { sm: 240 }, flexShrink: { sm: 0 } }}
          aria-label="mailbox folders"
        >
          <Drawer
            variant="temporary"
            open={open}
            onClose={handleDrawerToggle}
            ModalProps={{
              keepMounted: true,
            }}
            sx={{
              display: { xs: 'block', sm: 'none' },
              '& .MuiDrawer-paper': { boxSizing: 'border-box', width: 240 },
            }}
          >
            {drawer}
          </Drawer>
          <Drawer
            variant="permanent"
            sx={{
              display: { xs: 'none', sm: 'block' },
              '& .MuiDrawer-paper': { boxSizing: 'border-box', width: 240 },
            }}
            open
          >
            {drawer}
          </Drawer>
        </Box>
        <Box
          component="main"
          sx={{
            flexGrow: 1,
            p: 3,
            width: { sm: `calc(100% - ${240}px)` },
          }}
        >
          <Toolbar />
          <Typography paragraph>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Rhoncus mattis rhoncus
            urna neque viverra justo nec ultrices.
          </Typography>
        </Box>
      </Box>
    </ThemeProvider>
  );
}

// 5. Stepper Component
export function StepperExample() {
  const [activeStep, setActiveStep] = useState(0);

  const steps = [
    'Select campaign settings',
    'Create an ad group',
    'Create an ad',
  ];

  const handleNext = () => {
    setActiveStep((prevActiveStep) => prevActiveStep + 1);
  };

  const handleBack = () => {
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  const handleReset = () => {
    setActiveStep(0);
  };

  return (
    <Box sx={{ width: '100%', p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Stepper
      </Typography>

      <Stepper activeStep={activeStep} alternativeLabel>
        {steps.map((label) => (
          <Step key={label}>
            <StepLabel>{label}</StepLabel>
          </Step>
        ))}
      </Stepper>

      {activeStep === steps.length ? (
        <React.Fragment>
          <Typography sx={{ mt: 2, mb: 1 }}>
            All steps completed - you&apos;re finished
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
            <Box sx={{ flex: '1 1 auto' }} />
            <Button onClick={handleReset}>Reset</Button>
          </Box>
        </React.Fragment>
      ) : (
        <React.Fragment>
          <Typography sx={{ mt: 2, mb: 1 }}>
            Step {activeStep + 1}: {steps[activeStep]}
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'row', pt: 2 }}>
            <Button
              color="inherit"
              disabled={activeStep === 0}
              onClick={handleBack}
              sx={{ mr: 1 }}
            >
              Back
            </Button>
            <Box sx={{ flex: '1 1 auto' }} />
            <Button onClick={handleNext}>
              {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
            </Button>
          </Box>
        </React.Fragment>
      )}
    </Box>
  );
}

// 6. Advanced Table with Sorting
export function AdvancedTable() {
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<keyof typeof data>('calories');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);

  interface Data {
    calories: number;
    carbs: number;
    fat: number;
    name: string;
    protein: number;
  }

  function createData(
    name: string,
    calories: number,
    fat: number,
    carbs: number,
    protein: number,
  ): Data {
    return { name, calories, fat, carbs, protein };
  }

  const rows = [
    createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
    createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
    createData('Eclair', 262, 16.0, 24, 6.0),
    createData('Cupcake', 305, 3.7, 67, 4.3),
    createData('Gingerbread', 356, 16.0, 49, 3.9),
  ];

  const data = rows;

  const handleRequestSort = (
    event: React.MouseEvent<unknown>,
    property: keyof Data,
  ) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const visibleRows = useMemo(
    () =>
      [...data]
        .sort((a, b) =>
          order === 'asc' ? a[orderBy] - b[orderBy] : b[orderBy] - a[orderBy],
        )
        .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage),
    [order, orderBy, page, rowsPerPage],
  );

  return (
    <Box sx={{ width: '100%', p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Advanced Table
      </Typography>

      <Paper sx={{ width: '100%', mb: 2 }}>
        <TableContainer>
          <Table sx={{ minWidth: 750 }} aria-labelledby="tableTitle" size="medium">
            <TableHead>
              <TableRow>
                <TableCell>Dessert (100g serving)</TableCell>
                <TableCell align="right">Calories</TableCell>
                <TableCell align="right">Fat&nbsp;(g)</TableCell>
                <TableCell align="right">Carbs&nbsp;(g)</TableCell>
                <TableCell align="right">Protein&nbsp;(g)</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {visibleRows.map((row) => (
                <TableRow key={row.name}>
                  <TableCell component="th" scope="row">
                    {row.name}
                  </TableCell>
                  <TableCell align="right">{row.calories}</TableCell>
                  <TableCell align="right">{row.fat}</TableCell>
                  <TableCell align="right">{row.carbs}</TableCell>
                  <TableCell align="right">{row.protein}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>
    </Box>
  );
}

// 7. Modal Examples
export function ModalExamples() {
  const [open, setOpen] = useState(false);
  const [scroll, setScroll] = useState<'paper' | 'body'>('paper');

  const handleClickOpen = (scrollType: 'paper' | 'body') => () => {
    setOpen(true);
    setScroll(scrollType);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const descriptionElementRef = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    if (open) {
      const { current: descriptionElement } = descriptionElementRef;
      if (descriptionElement !== null) {
        descriptionElement.focus();
      }
    }
  }, [open]);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h5" gutterBottom>
        Modals
      </Typography>

      <Stack spacing={2} direction="row">
        <Button onClick={handleClickOpen('paper')}>scroll=paper</Button>
        <Button onClick={handleClickOpen('body')}>scroll=body</Button>
      </Stack>

      <Dialog
        open={open}
        onClose={handleClose}
        scroll={scroll}
        aria-labelledby="scroll-dialog-title"
        aria-describedby="scroll-dialog-description"
      >
        <DialogTitle id="scroll-dialog-title">Subscribe</DialogTitle>
        <DialogContent dividers={scroll === 'paper'}>
          <DialogContentText
            id="scroll-dialog-description"
            ref={descriptionElementRef}
            tabIndex={-1}
          >
            {[...new Array(50)]
              .map(
                () => `Cras mattis consectetur purus sit amet fermentum.
                Cras justo odio, dapibus ac facilisis in, egestas eget quam.
                Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
                Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`,
              )
              .join('')}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Cancel</Button>
          <Button onClick={handleClose}>Subscribe</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

// 8. Speed Dial
export function SpeedDialExample() {
  const [direction, setDirection] = useState<'up' | 'down' | 'left' | 'right'>('up');
  const [open, setOpen] = useState(false);

  const handleDirectionChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setDirection(event.target.value as 'up' | 'down' | 'left' | 'right');
  };

  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  const actions = [
    { icon: <Share />, name: 'Share' },
    { icon: <Print />, name: 'Print' },
    { icon: <Download />, name: 'Download' },
  ];

  return (
    <Box sx={{ p: 3, height: 320, transform: 'translateZ(0px)', flexGrow: 1 }}>
      <Typography variant="h5" gutterBottom>
        Speed Dial
      </Typography>

      <FormControl component="fieldset">
        <Typography component="legend">Direction</Typography>
        <RadioGroup row value={direction} onChange={handleDirectionChange}>
          <FormControlLabel value="up" control={<Radio />} label="Up" />
          <FormControlLabel value="right" control={<Radio />} label="Right" />
          <FormControlLabel value="down" control={<Radio />} label="Down" />
          <FormControlLabel value="left" control={<Radio />} label="Left" />
        </RadioGroup>
      </FormControl>

      <SpeedDial
        ariaLabel="SpeedDial example"
        sx={{ position: 'absolute', bottom: 16, right: 16 }}
        icon={<SpeedDialIcon />}
        onClose={handleClose}
        onOpen={handleOpen}
        open={open}
        direction={direction}
      >
        {actions.map((action) => (
          <SpeedDialAction
            key={action.name}
            icon={action.icon}
            tooltipTitle={action.name}
            onClick={handleClose}
          />
        ))}
      </SpeedDial>
    </Box>
  );
}

// 9. Advanced Layout Demo
export function AdvancedLayoutDemo() {
  return (
    <ThemeProvider theme={darkTheme}>
      <CssBaseline />
      <Container maxWidth="xl">
        <AppBar position="static">
          <Toolbar>
            <Typography variant="h6" sx={{ flexGrow: 1 }}>
              Advanced Layout
            </Typography>
            <Button color="inherit">Login</Button>
          </Toolbar>
        </AppBar>

        <Box sx={{ py: 4 }}>
          <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 3 }}>
            <Link underline="hover" color="inherit" href="/">
              Home
            </Link>
            <Link
              underline="hover"
              color="inherit"
              href="/material-ui/getting-started/installation/"
            >
              Core
            </Link>
            <Typography color="text.primary">Layout</Typography>
          </Breadcrumbs>

          <Grid container spacing={3}>
            <Grid item xs={12} md={8}>
              <AdvancedDataGrid />
              <Divider sx={{ my: 3 }} />
              <AdvancedTable />
            </Grid>
            <Grid item xs={12} md={4}>
              <StepperExample />
            </Grid>
          </Grid>

          <Box sx={{ mt: 3 }}>
            <DateTimePickers />
          </Box>

          <Box sx={{ mt: 3 }}>
            <ModalExamples />
          </Box>
        </Box>
      </Container>
    </ThemeProvider>
  );
}

// Main Advanced Showcase
export function AdvancedMaterialUiShowcase() {
  return (
    <Box>
      <AppLayout />
    </Box>
  );
}

export {
  darkTheme,
  customTheme,
  AdvancedDataGrid,
  DateTimePickers,
  AppLayout,
  StepperExample,
  AdvancedTable,
  ModalExamples,
  SpeedDialExample,
  AdvancedLayoutDemo,
  AdvancedMaterialUiShowcase
};

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

概览

用 Fundamentals 阅读独立组件片段,高级组件另有卡片。检查 FormExamples、ProgressExamples、TabExample,不挂载 React、加载图片或启动计时器。

一次阅读一个源码小节

本页卡片:Material-UI 基础; 高级Material-UI组件.

使用方式

  1. 1打开所列卡片,在页面阅读或复制源码到本地编辑器,定位下述小节。页面展示代码,并不是运行中的演示。

常见失败与 edge cases

  • 示例验证范围

    只检查状态算术与 JSX 声明,未运行 MUI 或验证布局;完整版本兼容另查。缓冲范围参考:https://v6.mui.com/material-ui/api/linear-progress/。

示例

1. 切换可见状态

如何使用

Material-UI 基础 — 从 showPassword=false、password 为空推演两次 handleClickShowPassword。

结果

标志 false→true→false,input 类型 password→text→password;密码字符串仍为空,没有认证操作。

2. 限制缓冲值

如何使用

Material-UI 基础 — 从 progress 90 推演两次回调,对比修复后的缓冲表达式。

结果

progress 为 90→100→0。Math.min(100,progress+10) 得 100、100、10,而原来是 100、110、10。回调次数不是实际计时。

3. 选择页签内容

如何使用

Material-UI 基础 — 在 TabExample 给 handleChange 代入 newValue=2,再代入 0。

结果

相等分支选择 Item Three content,再选 Item One content。数字索引是局部状态,不是跳转页面。

专题

软件标识符规范与格式校验

检查 UUID 结构、语义化版本语法和 URL slug 字符规则,并保留可复核证据;格式通过不等于全局唯一、资源可用或发布兼容。

专题

网页发布前无障碍审查

检查网页或 UI 组件的结构、阅读顺序、截图对比度和色觉风险,并把自动发现整理成由人工复核的发布记录。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

播客单集发布前音频与 RSS 一致性检查

将已完成的播客单集与 RSS 条目对照,核验最终文件字节数、类型及声明时长,再单独实测公开媒体地址与播放器表现。

首页
工具3216
案例593
可视化473
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web194

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Design

调色板提取器

从任何图片中提取精美的调色板,非常适合设计师从照片中寻找色彩灵感

UI 组件库

Chakra UI 示例

Chakra UI组件示例 - 简单、模块化和可访问的组件库,为您提供构建React应用程序所需的构建块

UI 组件库

Ant Design 示例

Ant Design组件示例 - 企业级UI设计语言和React UI库,包含丰富的高质量组件集

UI 组件库

shadcn/ui 示例

shadcn/ui组件示例 - 使用Radix UI和Tailwind CSS构建的漂亮、可访问、可定制的React组件