react 如何制作复选框
使用原生 HTML 和 React 状态管理
在 React 中可以通过 <input type="checkbox"> 结合状态管理实现复选框。通过 useState 钩子管理选中状态,onChange 事件更新状态。
import { useState } from 'react';
function CheckboxExample() {
const [isChecked, setIsChecked] = useState(false);
const handleChange = () => {
setIsChecked(!isChecked);
};
return (
<label>
<input
type="checkbox"
checked={isChecked}
onChange={handleChange}
/>
选择项
</label>
);
}
处理多选框组
对于多个复选框,可以使用对象或数组管理状态。通过动态生成复选框并绑定唯一标识符(如 id 或 value)实现批量操作。

import { useState } from 'react';
function CheckboxGroup() {
const [checkedItems, setCheckedItems] = useState({
option1: false,
option2: false,
});
const handleChange = (event) => {
const { name, checked } = event.target;
setCheckedItems(prev => ({
...prev,
[name]: checked
}));
};
return (
<div>
<label>
<input
type="checkbox"
name="option1"
checked={checkedItems.option1}
onChange={handleChange}
/>
选项一
</label>
<label>
<input
type="checkbox"
name="option2"
checked={checkedItems.option2}
onChange={handleChange}
/>
选项二
</label>
</div>
);
}
使用第三方库(如 Material-UI)
如果需要更丰富的样式和功能,可以使用 UI 库如 Material-UI 的 Checkbox 组件。
import { useState } from 'react';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
function MaterialCheckbox() {
const [checked, setChecked] = useState(false);
return (
<FormControlLabel
control={
<Checkbox
checked={checked}
onChange={(e) => setChecked(e.target.checked)}
color="primary"
/>
}
label="启用功能"
/>
);
}
自定义样式复选框
通过隐藏原生 <input> 并用自定义元素模拟视觉效果,结合 CSS 实现个性化设计。

import { useState } from 'react';
import './CustomCheckbox.css'; // 包含样式定义
function CustomCheckbox() {
const [checked, setChecked] = useState(false);
return (
<label className="custom-checkbox">
<input
type="checkbox"
checked={checked}
onChange={() => setChecked(!checked)}
className="hidden-input"
/>
<span className="checkmark"></span>
自定义样式选项
</label>
);
}
对应 CSS 示例(CustomCheckbox.css):
.hidden-input {
position: absolute;
opacity: 0;
}
.checkmark {
display: inline-block;
width: 20px;
height: 20px;
background-color: #eee;
margin-right: 8px;
border-radius: 4px;
}
.hidden-input:checked + .checkmark {
background-color: #2196F3;
}
.hidden-input:checked + .checkmark::after {
content: "✓";
color: white;
position: relative;
left: 4px;
}
与表单集成
在表单提交时获取复选框的值,通常需要将复选框绑定到表单状态管理(如 Formik 或 React Hook Form)。
import { useForm } from 'react-hook-form';
function FormWithCheckbox() {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data); // 包含复选框状态 { agree: true/false }
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>
<input
type="checkbox"
{...register('agree')}
/>
我同意条款
</label>
<button type="submit">提交</button>
</form>
);
}






