当前位置: 首页 > 工具软件 > Material UI > 使用案例 >

React Material-UI 可全选的 Checkbox

梁宏才
2023-12-01
const options = [ 'Selected Item 1', 'Selected Item 2', 'Selected Item 3'];

export default function App() {

  const [selected, setSelected] = useState([]);
  const isAllSelected = 
      options.length > 0 && selected.length === options.length;

  const handleChange = (event) => {
    const value = event.target.value;
    console.log(value)
    if (value === "all") {
      setSelected(selected.length === options.length ? [] : options);
      return;
    }
    const list = [...selected];
    const index = list.indexOf(value);
    index === -1 ? list.push(value) : list.splice(index, 1);
    setSelected(list);
  };  

  const listItem = options.map((option) => {        
    return (
        <div key={option}>
          <Checkbox 
            value={option}
            onChange={handleChange} 
            checked={selected.includes(option) } />
          <span>{option}</span>
        </div>
    )
  })

  return (
    <div style={{ display: 'flex', alignItems: 'center', margin: 10 }}>
        <Checkbox 
          value='all' 
          onChange={handleChange} 
          checked={isAllSelected} 
          />
        <span> Select All</span>
        {listItem}
    </div>
  );
}

 类似资料: