简体   繁体   English

如何在单击按钮时清除反应选择值而不将其添加到选项中?

[英]How to clear react-select values on button click without adding it to options?

I am using react-select and I want to clear the selected value on button click without adding it to the options property我正在使用react-select ,我想在单击按钮时清除所选值而不将其添加到options属性

I have tried我努力了

  1. Using state to manipulate the options property, but Apparently on calling clearValue() method, automatically pushes to the options array by default.使用 state 来操作选项属性,但显然在调用clearValue()方法时,默认情况下会自动推送到选项数组。

Problem问题

How do I tell react-select to just clear the selected values and not add it in the options array anywhere?我如何告诉react-select只清除所选值而不将其添加到选项数组中的任何地方?

import React, { useRef } from "react";
import Select from "react-select";

export default function App() {
  const selectInputRef = useRef();

  const onClear = () => {
    selectInputRef.current.select.clearValue();
  };

  return (
    <div className="App">
      <h1>Select Gender</h1>
      <Select
        isMulti
        ref={selectInputRef}
        options={[
          { value: "male", label: "Male" },
          { value: "female", label: "Female" }
        ]}
      />
      <button onClick={onClear}>Clear Value</button>
    </div>
  );
}

Here is my CodeSandbox Link这是我的CodeSandbox 链接

You need to manage the state of the selected values and the options yourself and manipulate it accordingly:您需要自己管理所选值和选项的 state 并相应地对其进行操作:

export default function App() {
  const [selected, setSelected] = useState([]);
  const [options, setOptions] = useState([
    { value: "male", label: "Male" },
    { value: "female", label: "Female" }
  ]);

  const handleClear = () => {
    setOptions((currentOptions) => currentOptions.filter((currentOption) => !selected.includes(currentOption)));
    setSelected([]);
  };

  return (
    <div className="App">
      <h1>Select Gender</h1>
      <Select isMulti value={selected} options={options} onChange={setSelected} />
      <button onClick={handleClear}>Clear Value</button>
    </div>
  );
}

编辑 react-select-clear-input(分叉)

Why not just add isClearable prop as:为什么不直接添加 isClearable 属性为:

<Select
  isMulti
  value={selected}
  options={options}
  onChange={setSelected}
  isClearable
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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