[英]How to set value of react-select with grouped options?
如何使用带有分组选项的react-select组件的 javascript 设置值? 在这篇文章中分组选项。
编辑回复@Tholle 的评论
我没有提到我正在使用 Typescript,因为我认为问题的答案往往较少。
这就是我使用组件的方式:
<Select
value={this.state.Industry}
options={this.industryOptions}
onChange={ (e) => this.handleChange("industry", e)}
></Select>
其中industryOptions 属于这种类型:
industryOptions: Array<{label: string, options: Array<{label: string, value: string}>}>
例如:
label: "Automotive"
options: Array(3)
0: {label: "Car brand", value: "77"}
1: {label: "Car dealer", value: "76"}
2: {label: "Other", value: "75"}
当在下拉列表中选择一个选项时 this.state.Industry 会改变,但是当 this.state.Industry 改变时 Select 组件没有任何反应。
我正在回答我自己的问题以供将来参考。 我意识到“值”应该与选项属于同一类型。 即这种类型的对象 {label: string, value: string},不是字符串。 所以我想我需要搜索一个具有相同价值的选项。 这是在我的组件(Select 的父级)的渲染函数中:
let indystryValue: {value: string, label: string}
let prospect: {value: string, label: string} | undefined;
this.industryOptions.forEach((io) => {
prospect = io.options.find((o) => o.value == this.state!.measurementBasics!.Industry.toString());
if(prospect !== undefined){
indystryValue = prospect;
}
});
...并将其放入 Select 中,如下所示:
<Select value={indystryValue!} ...
虽然我遇到了这个编译错误,但它正在工作:[ts] Type '{ value: string; 标签:字符串; }' 不可分配给类型 'ValueType<{ label: string; 选项:{标签:字符串; 值:字符串; }[]; }>'。 输入'{值:字符串; 标签:字符串; }' 不能分配给类型 '{ label: string; 选项:{标签:字符串; 值:字符串; }[]; }[]'。 类型“{ value: string;”中缺少属性“length” 标签:字符串; }'。 [2322] Select.d.ts(202, 3):预期类型来自属性“value”,该属性在此处声明的类型为“IntrinsicAttributes & IntrinsicClassAttributes> & Readonly<{ children?: ReactNode; }> & Readonly>' (JSX 属性) value?: ValueType<{ label: string; 选项:{标签:字符串; 值:字符串; }[]; }>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.