react 如何制作复选框
使用原生 HTML 复选框
在 React 中可以直接使用 HTML 的 <input type="checkbox"> 元素来创建复选框。通过 checked 和 onChange 属性控制状态:
function CheckboxExample() {
const [isChecked, setIsChecked] = React.useState(false);
return (
<label>
<input
type="checkbox"
checked={isChecked}
onChange={(e) => setIsChecked(e.target.checked)}
/>
Check me
</label>
);
}
自定义复选框组件
如果需要更灵活的样式控制,可以创建自定义复选框组件:
function CustomCheckbox({ checked, onChange, label }) {
return (
<label style={{ display: 'flex', alignItems: 'center' }}>
<div
style={{
width: 20,
height: 20,
border: '2px solid #333',
borderRadius: 4,
marginRight: 8,
backgroundColor: checked ? '#333' : 'transparent',
position: 'relative'
}}
>
{checked && (
<div style={{
position: 'absolute',
top: 2,
left: 6,
width: 5,
height: 10,
border: 'solid white',
borderWidth: '0 2px 2px 0',
transform: 'rotate(45deg)'
}} />
)}
</div>
<input
type="checkbox"
checked={checked}
onChange={onChange}
style={{ display: 'none' }}
/>
{label}
</label>
);
}
复选框组实现
处理多个复选框时,可以使用对象或数组来管理状态:
function CheckboxGroup() {
const [options, setOptions] = React.useState({
option1: false,
option2: false,
option3: false
});
const handleChange = (option) => {
setOptions(prev => ({
...prev,
[option]: !prev[option]
}));
};
return (
<div>
{Object.keys(options).map(option => (
<label key={option}>
<input
type="checkbox"
checked={options[option]}
onChange={() => handleChange(option)}
/>
{option}
</label>
))}
</div>
);
}
使用第三方库
对于更复杂的需求,可以使用现成的 React 复选框组件库:
material-ui提供的Checkbox组件antd的Checkbox组件react-checkbox等专门库
import { Checkbox } from '@material-ui/core';
function MaterialCheckbox() {
const [checked, setChecked] = React.useState(true);
return (
<Checkbox
checked={checked}
onChange={(e) => setChecked(e.target.checked)}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
);
}
无障碍访问
确保复选框遵循 WAI-ARIA 标准:
- 使用
<label>关联复选框 - 为自定义复选框添加适当的 ARIA 属性
- 确保键盘可操作
<label htmlFor="unique-id">
<input
id="unique-id"
type="checkbox"
aria-checked={isChecked}
checked={isChecked}
onChange={handleChange}
/>
Accessible checkbox
</label>






