react中checkbox实现单选
实现 React Checkbox 单选功能
在 React 中实现 Checkbox 的单选效果,可以通过状态管理和事件处理来控制选中状态。以下是两种常见方法:

使用状态管理单选
通过维护一个状态变量存储当前选中的值,点击 Checkbox 时更新状态:
import { useState } from 'react';
function RadioCheckbox() {
const [selectedValue, setSelectedValue] = useState(null);
const options = ['Option 1', 'Option 2', 'Option 3'];
const handleChange = (value) => {
setSelectedValue(value === selectedValue ? null : value);
};
return (
<div>
{options.map((option) => (
<label key={option}>
<input
type="checkbox"
checked={option === selectedValue}
onChange={() => handleChange(option)}
/>
{option}
</label>
))}
</div>
);
}
使用 radio 的样式实现
虽然技术上使用 radio 更合适,但若需要 Checkbox 的视觉样式:
function CheckboxAsRadio() {
const [selected, setSelected] = useState(null);
return (
<div>
{['A', 'B', 'C'].map((item) => (
<label key={item} style={{display: 'block'}}>
<input
type="checkbox"
style={{appearance: 'checkbox'}}
checked={item === selected}
onChange={() => setSelected(item)}
/>
{item}
</label>
))}
</div>
);
}
注意事项
- 单选逻辑需要手动处理,因为 Checkbox 设计是多选
- 清除已选项可通过判断当前点击是否已选中来实现
- 如需表单提交,建议使用 radio 按钮更符合语义
这两种方法都能实现视觉上的 Checkbox 单选效果,根据实际需求选择实现方式。






