You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让MUI Checkbox实现单选功能?(需保持复选框样式)

用MUI Checkbox实现单选功能的解决方案

核心思路

不用维护布尔数组,父组件只需要记录当前选中项的唯一标识(比如索引),通过props将选中状态和回调传递给子组件,子组件根据父组件的状态控制自身是否选中,点击时通知父组件更新选中项。

父组件实现

import { useState } from 'react';
import CheckboxComponent from './CheckboxComponent';

const ParentComponent = () => {
  // 用null表示未选中任何项,选中时存储对应子组件的索引
  const [selectedIndex, setSelectedIndex] = useState(null);

  // 处理子组件点击事件
  const handleCheckboxClick = (index) => {
    // 如果点击的是已选中的项,取消选中;否则选中该项
    setSelectedIndex(prev => prev === index ? null : index);
  };

  return (
    <>
      <CheckboxComponent 
        isChecked={selectedIndex === 0}
        onClick={() => handleCheckboxClick(0)}
        label="选项1"
      />
      <CheckboxComponent 
        isChecked={selectedIndex === 1}
        onClick={() => handleCheckboxClick(1)}
        label="选项2"
      />
      <CheckboxComponent 
        isChecked={selectedIndex === 2}
        onClick={() => handleCheckboxClick(2)}
        label="选项3"
      />
    </>
  );
};

export default ParentComponent;

子组件CheckboxComponent实现

import { Checkbox, FormControlLabel } from '@mui/material';

const CheckboxComponent = ({ isChecked, onClick, label }) => {
  return (
    <FormControlLabel
      control={
        <Checkbox
          checked={isChecked}
          onChange={onClick}
          // 保持原生复选框样式,无需修改为单选按钮组件
        />
      }
      label={label}
    />
  );
};

export default CheckboxComponent;

关键说明

  • 父组件通过selectedIndex精准控制选中项,避免了维护布尔数组时需要逐一重置其他项的麻烦,逻辑更简洁不易出错。
  • 子组件完全受控于父组件状态,仅负责渲染和触发点击回调,符合组件拆分的要求。
  • 严格保留MUI复选框的原生样式,未使用单选按钮组件,满足样式限制要求。

内容的提问来源于stack exchange,提问作者ABC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:50:26