[英]react-select use label as value passed to component instead of value from options array
[英]Can we use a value for defaultValue in react-select that is passed from another component as props?
傳遞的道具與選項數組中的道具具有相同的值。 我這樣做的原因是因為我正在使用模式來編輯一行。 數據從行傳遞到模態。 模態有選項,但我希望預先填充數據。 我似乎無法填充反應選擇下拉列表。 `options = [ { id: 0, value: 'New', label: 'New' }, { id: 1, value: '進行中', label: '進行中' }, { id: 2, value: '已阻止', label: '已阻止' }, { id: 3, value: '完成', label: '完成' } ];
getSelectedStatus = (status) => {
this.options.map((selected) => {
if (selected.value === status) {
this.setState({
selectedOption: selected.id
});
}
});
console.log(this.state.selectedOption);
};`
我像這樣使用 function 來獲取 selectedOption id,然后至少以這種方式傳遞給 render() 內的 defaultValue 屬性,但它不起作用。 有什么幫助嗎?
您需要在每個 onChange 事件上觸發所選選項。 如果您像我在下面分享的示例中那樣使用它,則可以通過調用其所有字段並在選項中發送數據來使用該組件。
static defaultProps = {
options: [],
components: undefined,
};
handleChange = (selectedOption) => {
const { onChange } = this.props;
onChange(selectedOption.value);
};
render() {
const {
value, name, options, components} = this.props;
return (
<Select
name={name}
value={(value === '') ? null : options.find(obj => obj.value ===
value)}
onChange={this.handleChange}
options={options}
className="react-select"
classNamePrefix="react-select"
/>
);
}
return (
<>
<SelectField
{...input}
options={options}
components={components}
/>
);
};
renderSelectField.defaultProps = {
options: [],
components: undefined,
};
您可以按如下方式在要使用的字段中發送數據。
options={data && data.map((values) => { return ({value: values?.id, label: values?.label}); })}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.