【问题标题】:How to set state of react-select component state when isMulti={true}?isMulti={true}时如何设置react-select组件状态?
【发布时间】:2020-04-19 18:41:50
【问题描述】:

这是我的部分代码:

我使用的表格:

const options = [
  { value: 'Orange', label: 'Orange' },
  { value: 'Banana', label: 'Banana' },
  { value: 'Apple', label: 'Apple' },
];

我创建状态“值”,它是一个初始状态为空表的表: 值:[]。

 private handleChange(value: any) {
    this.setState({ value: value });
  }

<Select
          value={this.props.selection}
          onChange={() => this.handleChange.bind(this)}
          options={options}
          isClearable={true}
          isMulti={true}
        />

{this.props.selection} 是以下类的类型:

export class Selection {
  value: string;
  label: string;

  constructor(
    value: string,
    label: string,
  ) {
    this.value = value;
    this.label = label;
  }
}

当我从 Select 组件中选择选项时,“值”状态不会改变。 你知道我做错了什么吗?

【问题讨论】:

    标签: typescript onchange setstate react-select


    【解决方案1】:

    您分配给的回调 每次更改 Select 中的值时,onChange={() =&gt; this.handleChange.bind(this)} 实际上并没有做任何事情。它唯一要做的就是将this 绑定到handleChange。它不会调用该函数。

    传递已经是函数的绑定结果就足够了。

    onChange={this.handleChange.bind(this)}

    考虑一下

    function sum(a,b){
       return a+b;
    }
    
    const sumWithNoArgs = () => sum.bind(null, 1,2);
    

    如果我们现在调用 sumWithNoArgs() 我们将得到一个新函数而不是 sum。这正是 select 所做的,它调用您传递的函数。

    你必须这样做

    const sumWithNoArgs = () => sum.bind(null, 1,2)();
    

    所以我们调用 SumWithNoArgs() 得到正确的结果。

    您需要在构造函数中绑定函数或将函数声明为类变量,以便自动绑定到您的类。

    【讨论】:

      猜你喜欢
      • 2022-07-14
      • 2019-02-17
      • 2019-09-23
      • 2016-12-30
      • 2020-12-14
      • 1970-01-01
      • 2018-01-02
      • 2016-09-27
      • 2018-08-26
      相关资源
      最近更新 更多