import React, { useState } from 'react';
const CheckboxList = ({ items, onSelectAll, onSelect }) => {
const [isSelectAll, setSelectAll] = useState(false);
const handleSelectAll = () => {
const isAllSelected = !isSelectAll;
setSelectAll(isAllSelected);
onSelectAll(isAllSelected);
};
const handleSelect = (item, isSelected) => {
onSelect(item, isSelected);
// 当所有子项目都被选中时,自动勾选全选复选框
const allSelected = items.every(i => i.isSelected);
if (allSelected !== isSelectAll) {
setSelectAll(allSelected);
}
};
return (
<>
<div>
<input
type="checkbox"
checked={isSelectAll}
onChange={handleSelectAll}
/>
<label>Select All</label>
</div>
{items.map(item => (
<div key={item.id}>
<input
type="checkbox"
checked={item.isSelected}
onChange={() => handleSelect(item, !item.isSelected)}
/>
<label>{item.label}</label>
</div>
))}
</>
);
};
// 使用示例
const items = [
{ id: 1, label: 'Item 1', isSelected: false },
{ id: 2, label: 'Item 2', isSelected: false },
{ id: 3, label: 'Item 3', isSelected: false },
];
const App = () => {
const [selectedItems, setSelectedItems] = useState(items);
const selectAllItems = isSelectAll => {
setSelectedItems(items =>
items.map(item => ({ ...item, isSelected: isSelectAll }))
);
};
const selectItem = (item, isSelected) => {
setSelectedItems(items =>
items.map(i => ({ ...i, isSelected: i.id === item.id ? isSelected : i.isSelected }))
);
};
return (
<CheckboxList
items={selectedItems}
onSelectAll={selectAllItems}
onSelect={selectItem}
/>
);
};
export default App;
这段代码实现了一个复选框列表组件CheckboxList
,其中包含全选复选框和单个复选框。当全选复选框被点击时,会触发onSelectAll
回调,并将所有单个复选框的选中状态更新为全选复选框的状态。同时,单个复选框的选中状态变化也会触发onSelect
回调,并更新组件状态。如果所有单个复选框都被选中,全选复选框也会自动被选中;如果有任何一个单个复选框未被选中,全选复选框也会被自动取消选中。这样就实现了全选复选框和单个复选框之间的联动功能。