我现在有以下数据:
[
{
"value": "G1-1",
"text": "One",
"optgroup": "Group 1
},
{
"value": "G1-2",
"text": "Two",
"optgroup": "Group 1"
},
{
"value": "G1-3",
"text": "Three",
"optgroup": "Group 1"
},
{
"value": "G1-4",
"text": "Four",
"optgroup": "Group 1"
},
{
"value": "G2-1",
"text": "One",
"optgroup": "Group 2"
},
{
"value": "G2-2",
"text": "Two",
"optgroup": "Group 2"
},
{
"value": "G2-3",
"text": "Three",
"optgroup": "Group 3"
},
{
"value": "G2-4",
"text": "Four",
"optgroup": "Group 4"
}
]
我将这些数据作为选项传递给我创建的简单Dropdown组件,如下所示:
const SelectInputRound = ({defaultOption, name, value, onChange, options}) => {
return (
<select
id={name}
className="inputSelectRound form-control override-fc"
name={name}
value={value}
onChange={onChange}>
<option className="defaultOption" value="">{defaultOption}</option>
{
options.map((option) => {
return <option key={option.value} value={option.value}>{option.text}</option>;
})
}
</select>
);
};
现在的问题是我不确定如何对选项进行分组并将其传递给控件,这样我就可以在组件中显示optgroup。
答案 0 :(得分:1)
现在的问题是我不确定如何对选项进行分组并将其传递给控件,这样我就可以在组件中显示optgroup。
在将数据传递到Dropdown
组件之前,您可以先对其进行转换以对数据进行相应的分组。例如,这样。
const options = [
{
value: "G1-1",
text: "One",
optgroup: "Group 1"
},
{
value: "G2-2",
text: "Two",
optgroup: "Group 2"
},
{
value: "G2-3",
text: "Three",
optgroup: "Group 3"
},
{
value: "G2-4",
text: "Four",
optgroup: "Group 4"
}
];
const groupedOptions = {};
options.forEach(option => {
if (!groupedOptions[option.optgroup]) groupedOptions[option.optgroup] = [];
groupedOptions[option.optgroup].push({
value: option.value,
text: option.text
});
});
console.log(groupedOptions);
不过,您还必须修改Dropdown
组件,以便与其期望options
是props
之一,而应该期望一组选项。
const renderOptions = options => {
return options.map(option => {
return (
<option key={option.value} value={option.value}>
{option.text}
</option>
);
});
};
const SelectInputRound = ({
defaultOption,
name,
value,
onChange,
groupedOptions
}) => {
return (
<select
id={name}
className="inputSelectRound form-control override-fc"
name={name}
value={value}
onChange={onChange}
>
{Object.keys(groupedOptions).map((group, index) => {
return (
<optgroup key={index} label={group}>
{renderOptions(groupedOptions[group])}
</optgroup>
);
})}
</select>
);
};
请参阅工作示例here.