AntD Checkbox 的三種狀態處理

  • 對於單個 Checkbox 來講,只有兩種值:選中 (checked) 或未選中 (unchecked) 。
  • 但對於 Checkbox Group 來講,卻有三種值:全選 (checked) 、部分選中 (indeterminate) 、未選中(unchecked)
AntD 對於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變成兩種狀態
  1. 去掉全選checkboxindeterminate屬性便可
  2. 改變下onChangesetCheckAll的判斷條件
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')); 複製代碼

CodeSandBox-Checkbox Group 兩種狀態的實現css

相關文章
相關標籤/搜索