MUI快速入门

858 阅读1分钟

MUI 快速入门指南:核心原理与实战开发

什么是 MUI?

MUI(Material-UI)是基于 Google Material Design 的 React UI 组件库,提供丰富的预制组件和强大的样式定制能力。最新版本(v6.x)采用 emotion/styled-components 作为样式引擎。

核心原理

1. 组件化架构

// 典型组件使用示例
import Button from '@mui/material/Button';

function App() {
  return <Button variant="contained">Hello World</Button>;
}

2. CSS-in-JS 样式方案

// 使用 styled API 创建自定义组件
import { styled } from '@mui/material/styles';

const RedButton = styled(Button)({
  backgroundColor: 'red',
  '&:hover': {
    backgroundColor: 'darkred'
  }
});

3. 主题系统

// 主题配置示例
import { createTheme, ThemeProvider } from '@mui/material/styles';

const theme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
    },
  },
});

// 应用主题
<ThemeProvider theme={theme}>
  <App />
</ThemeProvider>

快速开发指南

1. 环境搭建

npm install @mui/material @emotion/react @emotion/styled

2. 基础组件使用

// 表单组件示例
import { TextField, Checkbox, Slider } from '@mui/material';

function BasicForm() {
  return (
    <div>
      <TextField label="Name" variant="outlined" />
      <Checkbox defaultChecked color="primary" />
      <Slider defaultValue={30} />
    </div>
  );
}

3. 布局系统

// 使用 Grid 组件布局
import Grid from '@mui/material/Grid';

function ResponsiveLayout() {
  return (
    <Grid container spacing={2}>
      <Grid item xs={12} sm={6} md={4}>
        <div>Item 1</div>
      </Grid>
      <Grid item xs={12} sm={6} md={4}>
        <div>Item 2</div>
      </Grid>
    </Grid>
  );
}

4. 主题定制

// 扩展主题配置
const customTheme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          borderRadius: '8px'
        }
      }
    }
  }
});

高级技巧

1. 响应式设计

// 使用 useMediaQuery 钩子
import useMediaQuery from '@mui/material/useMediaQuery';

function ResponsiveComponent() {
  const matches = useMediaQuery('(min-width:600px)');

  return <div>{matches ? 'Desktop' : 'Mobile'}</div>;
}

2. 动态样式

// 使用 sx prop 快速样式
<Button
  sx={{
    bgcolor: 'error.main',
    '&:hover': { bgcolor: 'error.dark' }
  }}
>
  Danger Button
</Button>

3. 自定义组件

// 创建复合组件
import Box from '@mui/material/Box';

const Card = ({ children }) => (
  <Box 
    sx={{
      p: 2,
      border: '1px solid #ddd',
      borderRadius: 2,
      boxShadow: 1
    }}
  >
    {children}
  </Box>
);

最佳实践

  1. 优先使用主题配置进行全局样式设置
  2. 合理组合基础组件创建业务组件
  3. 使用 sx prop 进行快速原型开发
  4. 通过组件覆写(styleOverrides)进行细粒度控制

学习资源