预期实现的效果
列表项部分选中时,checkall处于半选状态,点击checkall要么全选,要么全不选。
列表项类型
declare type TableRow = {
key: Key
title: string
isSelected?: boolean
}
示范数据
const [tabledata, setTabledata] = useState<TableRow[]>([])
useEffect(()=>{
setTabledata([
{key:1,title:'Apple'},
{key:2,title:'Pear'},
{key:3,title:'Orange'}
])
},[])
核心控制函数
//半选状态
const halfChecked = useMemo(() => {
if (!tabledata.length) {
return false
}
let checkeds = tabledata.filter(d => d.isSelected).length
return checkeds > 0 && checkeds < tabledata.length
}, [tabledata])
//全选状态
const allChecked = useMemo(() => {
if (!tabledata.length) {
return false
}
return tabledata.every(d => d.isSelected)
}, [tabledata])
//全选控制,点一下全选或全不选
function handleCheckAll(e: CheckboxChangeEvent) {
if (e.target.checked) {
tabledata.forEach(d => d.isSelected = true)
} else {
tabledata.forEach(d => d.isSelected = false)
}
setTabledata([...tabledata])
}
//列表项选中改变事件
function handleItemSelect(item:TableRow){
item.isSelected =!item.isSelected
setTabledata([...tabledata])
}
视图部分
<Checkbox indeterminate={halfChecked} checked={allChecked} onChange={handleCheckAll}>Check All</Checkbox>
<ul>
{
tabledata.map(row=>(
<li key={row.key}>
<Checkbox checked={row.isSelected} onChange={()=>handleItemSelect(row)}>{row.title}</Checkbox>
</li>
))
}
</ul>