Javascript 如何以编程方式清除/重置 React-Select?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50412843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:36:19  来源:igfitidea点击:

How to programmatically clear/reset React-Select?

javascriptreactjsfunctional-programmingreact-hooksreact-select

提问by Marc

ReactSelect V2and V3seems to have several props like clearValue, resetValueand setValue. Whatever I'm trying, I'm not able to clear the selections programmatically. resetValueseems not to be accessible from the outside.

ReactSelect V2V3似乎有几个道具,如clearValue,resetValuesetValue。无论我在尝试什么,我都无法以编程方式清除选择。resetValue似乎无法从外部访问。

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?

我在这里错过了什么还是还没有完全实施?

回答by Artur N

If you're using react-selectyou can try to pass nullto valueprop.

如果您使用的是react-select,您可以尝试传递nullvalueprop。

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'sa working example of this.

这是一个工作示例。

回答by TPHughes

I came across this problem myself and managed to fix it by passing a keyto the React-Select component, with the selected value appended to it. This will then force the ReactSelectto re-render itself when the selection is updated.

我自己遇到了这个问题,并设法通过将 a 传递key给 React-Select 组件来解决它,并将选定的值附加到它。这将ReactSelect在选择更新时强制重新渲染自身。

I hope this helps someone.

我希望这可以帮助别人。

import ReactSelect from 'react-select';

...

<ReactSelect
  key={`my_unique_select_key__${selected}`}
  value={selected || ''}
  ...
/>

回答by Mahipal Reddy

Just store the value in the state, and change the state programmatically using componentDidUpdate etc...

只需将值存储在状态中,然后使用 componentDidUpdate 等以编程方式更改状态...

class Example extends Component {

constructor() {
    super()
}

state = {
     value: {label: 'Default value', key : '001'}
}

render() {
   return(
      <Select
         ...
         value={this.state.value}
         ...
      />
   )
)}

Note: 'value' should be an object.

注意:'value' 应该是一个对象。

回答by Kira

If someone looking for solution using Hooks. React-Select V3.05:

如果有人正在寻找使用 Hooks 的解决方案。反应选择 V3.05:

const initial_state = { my_field: "" }

const my_field_options = [
    { value: 1, label: "Daily" },
    { value: 2, label: "Weekly" },
    { value: 3, label: "Monthly" },
]

export default function Example(){
    const [values, setValues] = useState(initial_state);

    function handleSelectChange(newValue, actionMeta){
        setValues({
            ...values,
            [actionMeta.name]: newValue ? newValue.value : ""
        })
    }

    return <Select
               name={"my_field"}
               inputId={"my_field"}
               onChange={handleSelectChange}
               options={my_field_options}
               placeholder={values.my_field}
               isClearable={true}
           /> 
}

回答by Andrea Ligios

This is my working implementation of a React-Select V3cleared programmaticallywith Hooks.

这是我使用Hooks 以编程方式清除React-Select V3 的工作实现。

You can play with it in the CodeSandbox DEMO. Any feedback is welcome.

您可以在CodeSandbox DEMO 中使用它。欢迎任何反馈。

const initialFormState = { mySelectKey: null };

const [myForm, setMyForm] = useState(initialFormState);

const updateForm = value => {
  setMyForm({ ...myForm, mySelectKey: value });
};

const resetForm = () => {
  setMyForm(initialFormState);
};

return (
  <div className="App">
    <form>

      <Select name = "mySelect"
           options = {options}
             value = {options.filter(({ value }) => value === myForm.mySelectKey)}
    getOptionLabel = {({ label }) => label}
    getOptionValue = {({ value }) => value}
          onChange = {({ value }) => updateForm(value)} />

      <p>MyForm: {JSON.stringify(myForm)}</p>

      <input type="button" value="Reset fields" onClick={resetForm} />

    </form>
  </div>
);

回答by Pixelomo

In case it helps anyone, this is my solution: I created a button to clear the selected value by setting state back to it's initial value.

如果它对任何人有帮助,这是我的解决方案:我创建了一个按钮,通过将状态设置回其初始值来清除所选值。

<button onClick={() => this.clearFilters()} >Clear</button>

clearFilters(){
    this.setState({ startTime: null })
}

Full code sample below:

完整代码示例如下:

import React from "react"
import Select from 'react-select';

const timeSlots = [
    { value: '8:00', label: '8:00' },
    { value: '9:00', label: '9:00' },
    { value: '10:00', label: '10:00' },
] 

class Filter extends React.Component {

  constructor(){
    super();
    this.state = {
      startTime: null,
    }
  }
  
  startTime = (selectedTime) => {
    this.setState({ startTime: selectedTime });
  }

  clearFilters(){
    this.setState({
        startTime: null, 
    })
  }

  render(){
    const { startTime } = this.state;
    
    return(
      <div>
        <button onClick={() => this.clearFilters()} >Clear</button>
        <Select
            value={startTime}
            onChange={this.startTime}
            options={timeSlots}
            placeholder='Start time'
        />
      </div>
    )
  }

}

export default Filter

回答by Vladislav Sorokin

If you check Select component in React Developers panel you will see that it is wrapped by another – State Manager. So you ref is basically ref to State manager, but not to Select itself.

如果您在 React Developers 面板中选中 Select 组件,您将看到它被另一个 - 状态管理器包装。所以你 ref 基本上是对 State manager 的 ref,而不是 Select 本身。

enter image description here

在此处输入图片说明

Luckily, StateManager has state) and a value object which you may set to whatever you want.

幸运的是,StateManager 有状态)和一个值对象,您可以将其设置为您想要的任何值。

For example (this is from my project, resetGroup is onClick handler that I attach to some button in DOM):

例如(这是来自我的项目,resetGroup 是我附加到 DOM 中某个按钮的 onClick 处理程序):

<Select onChange={this.handleGroupSelect} 
      options={this.state.groupsName.map(group => 
                  ({ label: group, value: group }) )}
      instanceId="groupselect"
      className='group-select-container'
      classNamePrefix="select"
      placeholder={this.context.t("Enter name")}
      ref={c => (this.groupSelect = c)}
/>

    resetGroup = (e) => {
        e.preventDefault()
        this.setState({
            selectedGroupName: ""
        })
        this.groupSelect.state.value.value = ""
        this.groupSelect.state.value.label = this.context.t("Enter name")
    }

回答by Bogdan

A simple option would be to pass nullto the valueprop.

一个简单的选择是传递nullvalue道具。

<Select value={null} />

回答by Mohamed Emam

I use redux-observable.

我使用 redux-observable。

Initial state:

初始状态:

firstSelectData: [],
secondSelectData:[],
secondSelectValue: null

I create an action for filling first select. on change of first select, I call an action to fill second one.

我创建了一个填充第一个选择的动作。在改变第一个选择时,我调用一个动作来填充第二个。

In success of fill first select I set (secondSelectDatato [], secondSelectValueto null)

成功填充首先选择我设置(secondSelectDatato []secondSelectValueto null

In success of fill second select I set (secondSelectValueto null) on change of second select, I call an action to update secondSelectValuewith the new value selected

在成功填充第二个选择我设置(secondSelectValuenull)更改第二个选择时,我调用一个操作来更新secondSelectValue选择的新值