Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

javascript - How to programmatically clear/reset React-Select?

ReactSelect V2 and V3 seems to have several props like clearValue, resetValue and setValue. Whatever I'm trying, I'm not able to clear the selections programmatically. resetValue seems not to be accessible from the outside.

selectRef.setValue([], 'clear')
// or
selectRef.clearValue()

This does not clear the current selection.

Do I miss something here or is it not fully implemented yet?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're using react-select you can try to pass null to value prop.

For example:

import React from "react";
import { render } from "react-dom";
import Select from "react-select";

class App extends React.Component {
  constructor(props) {
    super(props);

    const options = [
      { value: "one", label: "One" },
      { value: "two", label: "Two" }
    ];

    this.state = {
      select: {
        value: options[0], // "One" as initial value for react-select
        options // all available options
      }
    };
  }

  setValue = value => {
    this.setState(prevState => ({
      select: {
        ...prevState.select,
        value
      }
    }));
  };

  handleChange = value => {
    this.setValue(value);
  };

  handleClick = () => {
    this.setValue(null); // here we reset value
  };

  render() {
    const { select } = this.state;

    return (
      <div>
        <p>
          <button type="button" onClick={this.handleClick}>
            Reset value
          </button>
        </p>
        <Select
          name="form-field-name"
          value={select.value}
          onChange={this.handleChange}
          options={select.options}
        />
      </div>
    );
  }
}

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

Here's a working example of this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...