如何以编程方式清除/重置 React-Select? [英] How to programmatically clear/reset React-Select?

查看:33
本文介绍了如何以编程方式清除/重置 React-Select?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这不会清除当前选择.

我是否遗漏了一些东西,或者它还没有完全实施?

解决方案

如果你正在使用 react-select 你可以尝试将 null 传递给 value 属性.

例如:

从react"导入React;从react-dom"导入{渲染};导入从反应选择"中选择;类 App 扩展了 React.Component {构造函数(道具){超级(道具);常量选项 = [{ 值:一",标签:一"},{ 值:两个",标签:两个"}];this.state = {选择: {value: options[0],//"One" 作为 react-select 的初始值options//所有可用的选项}};}setValue = 值 =>{this.setState(prevState => ({选择: {...prevState.select,价值}}));};handleChange = 值 =>{this.setValue(value);};handleClick = () =>{this.setValue(null);//这里我们重置值};使成为() {const { 选择 } = this.state;返回 (<div><p><button type="button" onClick={this.handleClick}>重置值</p><选择名称=表单字段名称"价值={选择.价值}onChange={this.handleChange}选项={select.options}/>

);}}render(, document.getElementById("root"));

这是一个工作示例.

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?

解决方案

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.

这篇关于如何以编程方式清除/重置 React-Select?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆