简体   繁体   中英

Antd Multi Select Clear Button

Below is the basic code from the antd website about creating a multi select option. What I want to achieve is create a 'clear' button. When clicking clear it will remove all the boxes with the 'x' that say a10, b12, etc. How do I clear out the box?

I don't want to use allowClear, I want to tie this to my own button

https://codesandbox.io/s/g0dec

const { Select } = antd;

const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

function handleChange(value) {
  console.log(`selected ${value}`);
}

ReactDOM.render(
  <Select
    mode="multiple"
    style={{ width: '100%' }}
    placeholder="Please select"
    defaultValue={['a10', 'c12']}
    onChange={handleChange}
  >
    {children}
  </Select>,
  mountNode,
);

You can do this by making Select controlled component. This is how you can do this by using value prop of Select and useState hook.

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";

const { Option } = Select;

const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

const App = () => {
  const defaultValues = ["a10", "c12"];
  const [selectedValues, setSelectedValues] = useState(defaultValues);

  function handleChange(value) {
    console.log(`selected ${value}`);
    setSelectedValues(value);
  }

  const handleClear = () => {
    setSelectedValues([]);
  };

  return (
    <div>
      <Select
        mode="multiple"
        style={{ width: "100%" }}
        placeholder="Please select"
        defaultValue={selectedValues}
        onChange={handleChange}
        value={selectedValues}
      >
        {children}
      </Select>
      <span>
        <button onClick={handleClear}>Clear</button>
      </span>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));  

Working example here: https://codesandbox.io/s/inspiring-cherry-z6zh0

You can add the allowClear prop like so:

<Select
    mode="multiple"
    style={{ width: '100%' }}
    placeholder="Please select"
    defaultValue={['a10', 'c12']}
    onChange={handleChange}
    allowClear
  >
    {children}
  </Select>

It will show up a clear button at the right side of the input when you hover it.

You can find it in the antd docs of the Select input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM