Material UI Toggle Button 使用详解

class Toggle Button

Material UI 的 Toggle Button 组件是一种非常直观和用户友好的控件,允许用户在两种状态之间进行切换。它常用于开关功能、选项选择等场景。本文将详细介绍 Toggle Button 的使用,包括基本用法、所有属性和方法的详细解释,以及与其他组件的结合示例。

1. Toggle Button 的基本用法

1.1 安装 Material UI

确保您已经安装了 Material UI。如果还没有,可以通过以下命令进行安装:

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

1.2 Toggle Button 基础示例

下面是一个简单的 Toggle Button 示例,展示了如何使用该组件。

import React, { useState } from 'react';
import { ToggleButton, ToggleButtonGroup } from '@mui/material';

const ToggleButtonExample = () => {
  const [alignment, setAlignment] = useState('left');

  const handleAlignment = (event, newAlignment) => {
    if (newAlignment !== null) {
      setAlignment(newAlignment);
    }
  };

  return (
    <ToggleButtonGroup
      value={alignment}
      exclusive
      onChange={handleAlignment}
      aria-label="text alignment"
    >
      <ToggleButton value="left" aria-label="left aligned">
        左对齐
      </ToggleButton>
      <ToggleButton value="center" aria-label="center aligned">
        居中
      </ToggleButton>
      <ToggleButton value="right" aria-label="right aligned">
        右对齐
      </ToggleButton>
    </ToggleButtonGroup>
  );
};

export default ToggleButtonExample;

代码解析

  • useState: 用于管理 Toggle Button 的状态。
  • ToggleButtonGroup: 允许一组 Toggle Buttons 互相排斥,形成单选效果。
  • ToggleButton: 表示可切换的按钮。

2. Toggle Button 属性与方法

2.1 主要属性

  • value: 当前选中的 Toggle Button 的值。
  • exclusive: 如果为 true,Toggle Button Group 将只允许选择一个按钮。
  • onChange: 当选择的按钮发生变化时的回调函数。

2.2 主要方法

  • handleAlignment(event, newAlignment): 用于更新状态的方法,当用户点击按钮时调用。

3. 结合其他组件使用

3.1 结合 Checkbox 组件

将 Toggle Button 与 Checkbox 结合,允许用户选择多个选项。

import React, { useState } from 'react';
import {
  ToggleButton,
  ToggleButtonGroup,
  Checkbox,
  Typography,
  Box,
} from '@mui/material';

const ToggleButtonWithCheckbox = () => {
  const [alignment, setAlignment] = useState('left');
  const [checkedItems, setCheckedItems] = useState([true, false, false]);

  const handleAlignment = (event, newAlignment) => {
    if (newAlignment !== null) {
      setAlignment(newAlignment);
    }
  };

  const handleCheckboxChange = (index) => {
    const updatedItems = [...checkedItems];
    updatedItems[index] = !updatedItems[index];
    setCheckedItems(updatedItems);
  };

  return (
    <Box>
      <Typography variant="h6">选择对齐方式</Typography>
      <ToggleButtonGroup
        value={alignment}
        exclusive
        onChange={handleAlignment}
        aria-label="text alignment"
      >
        <ToggleButton value="left" aria-label="left aligned">
          左对齐
        </ToggleButton>
        <ToggleButton value="center" aria-label="center aligned">
          居中
        </ToggleButton>
        <ToggleButton value="right" aria-label="right aligned">
          右对齐
        </ToggleButton>
      </ToggleButtonGroup>
      <Box mt={2}>
        <Typography variant="h6">选择项目</Typography>
        {['项目 A', '项目 B', '项目 C'].map((item, index) => (
          <Box key={item}>
            <Checkbox
              checked={checkedItems[index]}
              onChange={() => handleCheckboxChange(index)}
            />
            {item}
          </Box>
        ))}
      </Box>
    </Box>
  );
};

export default ToggleButtonWithCheckbox;

代码解析

  • Checkbox: 用于显示多选选项,与 Toggle Button 结合使用。
  • handleCheckboxChange: 更新选中的复选框状态。

3.2 结合 Form 组件

将 Toggle Button 嵌入到 Form 中,允许用户提交选项。

import React, { useState } from 'react';
import {
  Box,
  Button,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
  Typography,
} from '@mui/material';

const ToggleButtonForm = () => {
  const [alignment, setAlignment] = useState('left');
  const [name, setName] = useState('');

  const handleAlignment = (event, newAlignment) => {
    if (newAlignment !== null) {
      setAlignment(newAlignment);
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`选择的对齐方式: ${alignment},姓名: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <Typography variant="h6">选择对齐方式</Typography>
      <ToggleButtonGroup
        value={alignment}
        exclusive
        onChange={handleAlignment}
        aria-label="text alignment"
      >
        <ToggleButton value="left" aria-label="left aligned">
          左对齐
        </ToggleButton>
        <ToggleButton value="center" aria-label="center aligned">
          居中
        </ToggleButton>
        <ToggleButton value="right" aria-label="right aligned">
          右对齐
        </ToggleButton>
      </ToggleButtonGroup>
      <Box mt={2}>
        <TextField
          label="姓名"
          variant="outlined"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </Box>
      <Button variant="contained" color="primary" type="submit" sx={{ mt: 2 }}>
        提交
      </Button>
    </form>
  );
};

export default ToggleButtonForm;

代码解析

  • TextField: 用于用户输入姓名。
  • handleSubmit: 处理表单提交逻辑,展示所选对齐方式和姓名。

4. 进阶使用

4.1 自定义样式

您可以通过使用 sx 属性或者自定义 CSS 类来修改 Toggle Button 的样式。例如:

<ToggleButton 
  value="left" 
  aria-label="left aligned" 
  sx={{ borderRadius: '20px', bgcolor: alignment === 'left' ? 'primary.main' : 'grey.200' }}
>
  左对齐
</ToggleButton>

4.2 结合 Snackbar 组件

当用户选择 Toggle Button 后,显示 Snackbar 提示。

import React, { useState } from 'react';
import {
  ToggleButton,
  ToggleButtonGroup,
  Snackbar,
  Button,
  Typography,
  Box,
} from '@mui/material';

const ToggleButtonWithSnackbar = () => {
  const [alignment, setAlignment] = useState('left');
  const [open, setOpen] = useState(false);

  const handleAlignment = (event, newAlignment) => {
    if (newAlignment !== null) {
      setAlignment(newAlignment);
      setOpen(true);
    }
  };

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

  return (
    <Box>
      <Typography variant="h6">选择对齐方式</Typography>
      <ToggleButtonGroup
        value={alignment}
        exclusive
        onChange={handleAlignment}
        aria-label="text alignment"
      >
        <ToggleButton value="left" aria-label="left aligned">
          左对齐
        </ToggleButton>
        <ToggleButton value="center" aria-label="center aligned">
          居中
        </ToggleButton>
        <ToggleButton value="right" aria-label="right aligned">
          右对齐
        </ToggleButton>
      </ToggleButtonGroup>
      <Snackbar
        open={open}
        autoHideDuration={3000}
        onClose={handleClose}
        message={`您选择了 ${alignment} 对齐方式`}
        action={
          <Button color="inherit" onClick={handleClose}>
            关闭
          </Button>
        }
      />
    </Box>
  );
};

export default ToggleButtonWithSnackbar;

代码解析

  • Snackbar: 显示用户选择的对齐方式。
  • handleClose: 关闭 Snackbar 的函数。

5. 小结

本文详细探讨了 Material UI 的 Toggle Button 组件的使用,包括基本用法、所有属性和方法,以及与其他组件的结合示例。通过这些示例,您可以清晰地了解如何在项目中实现 Toggle Button,并根据需要进行自定义。

希望这篇文章能帮助您更好地理解和使用 Material UI 的 Toggle Button 组件。如果您有任何问题或需要进一步的帮助,请随时与我交流!

chat评论区
评论列表
menu