Checkbox Group
的實現以下import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];
const App = () => {
const [checkedList, setCheckedList] = useState(defaultCheckedList);
const [indeterminate, setIndeterminate] = useState(true);
const [checkAll, setCheckAll] = useState(false);
const onChange = checkedList => {
setCheckedList(checkedList);
setIndeterminate(
!!checkedList.length && checkedList.length < plainOptions.length
);
setCheckAll(checkedList.length === plainOptions.length);
};
const onCheckAllChange = e => {
setCheckedList(e.target.checked ? plainOptions : []);
setIndeterminate(false);
setCheckAll(e.target.checked);
};
return (
<div> <div style={{ borderBottom: '1px solid #E9E9E9' }}> <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll} > Check all </Checkbox> </div> <br /> <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} /> </div> ); }; ReactDOM.render(<App />, document.getElementById('container')); 複製代碼
CodeSandBox-Checkbox Group 三種狀態的實現javascript
Checkbox Group
變成兩種狀態checkbox
的indeterminate
屬性便可onChange
裏setCheckAll
的判斷條件const onChange = checkedList => {
setCheckedList(checkedList);
setCheckAll(checkedList.length !== 0);
};
複製代碼
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = [];
const App = () => {
const [checkedList, setCheckedList] = useState(defaultCheckedList);
const [checkAll, setCheckAll] = useState(false);
const onChange = checkedList => {
setCheckedList(checkedList);
setCheckAll(checkedList.length !== 0);
};
const onCheckAllChange = e => {
setCheckedList(e.target.checked ? plainOptions : []);
setCheckAll(e.target.checked);
};
return (
<div> <div style={{ borderBottom: '1px solid #E9E9E9' }}> <Checkbox onChange={onCheckAllChange} checked={checkAll}> Check all </Checkbox> </div> <br /> <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} /> </div> ); }; ReactDOM.render(<App />, document.getElementById('container')); 複製代碼