isMulti={true}时如何设置react-select组件状态?
How to set state of react-select component state when isMulti={true}?
这是我的部分代码:
Table 我用的是:
const options = [
{ value: 'Orange', label: 'Orange' },
{ value: 'Banana', label: 'Banana' },
{ value: 'Apple', label: 'Apple' },
];
我创建状态 "value",它是一个 table,初始状态为空 table:
值:[].
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} 是以下类型 class:
export class Selection {
value: string;
label: string;
constructor(
value: string,
label: string,
) {
this.value = value;
this.label = label;
}
}
当我从 Select 组件 select 选项时,"value" 状态不会改变。
你知道我做错了什么吗?
您要分配给的回调
每次您更改 Select 中的值时,onChange={() => 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() ,我们将得到一个新函数而不是求和。这正是 select 所做的,它调用您传递的函数。
你必须做
const sumWithNoArgs = () => sum.bind(null, 1,2)();
所以我们调用 SumWithNoArgs() 得到正确的结果。
您需要在构造函数中绑定您的函数,或者将函数声明为 class 变量,以便它自动绑定到您的 class。
这是我的部分代码:
Table 我用的是:
const options = [
{ value: 'Orange', label: 'Orange' },
{ value: 'Banana', label: 'Banana' },
{ value: 'Apple', label: 'Apple' },
];
我创建状态 "value",它是一个 table,初始状态为空 table: 值:[].
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} 是以下类型 class:
export class Selection {
value: string;
label: string;
constructor(
value: string,
label: string,
) {
this.value = value;
this.label = label;
}
}
当我从 Select 组件 select 选项时,"value" 状态不会改变。 你知道我做错了什么吗?
您要分配给的回调
每次您更改 Select 中的值时,onChange={() => 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() ,我们将得到一个新函数而不是求和。这正是 select 所做的,它调用您传递的函数。
你必须做
const sumWithNoArgs = () => sum.bind(null, 1,2)();
所以我们调用 SumWithNoArgs() 得到正确的结果。
您需要在构造函数中绑定您的函数,或者将函数声明为 class 变量,以便它自动绑定到您的 class。