我们可以在react select中使用defaultValue的值吗?该值是作为道具从另一个组件传递的



传递的道具与选项数组中的道具具有相同的值。我之所以这样做,是因为我使用模态来编辑一行。数据从一行传递到模态。Modal有选项,但我希望数据是预先填充的。我似乎无法填充react-select下拉列表。`选项=[{id:0,值:"New",标签:"New"},{id:1,值:"正在进行",标签:"正在处理"},{id:2,值:"Blocked",标签:"Blocked'"},{id:3,值:"Complete",标签:"Complete"}];

getSelectedStatus = (status) => {
this.options.map((selected) => {
if (selected.value === status) {
this.setState({
selectedOption: selected.id
});
}
});
console.log(this.state.selectedOption);
};`

我使用了这样一个函数来获取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}); })}

最新更新