嗨,我有 2 个下拉菜单,但为此我正在管理 2 个状态。请帮我减少重复的代码。假设,如果我想要 10 个下拉菜单,那么我的状态数和相同的方法会重复相同。如果有办法重构代码以减少状态和方法的数量会更好。
注意:我有一个基于类的组件
this.state = {
isOpen: false,
selected: null,
isDisabled: false,
isOpen1: false,
selected1: null,
isDisabled1: false,
isOpen2: false,
selected2: null,
isDisabled2: false, }
内部构造函数
this.options = [
<SelectOption key={0} value={hourTxt} isPlaceholder />,
<SelectOption key={1} value={weekTxt} />,
<SelectOption key={2} value={dayTxt} />,
<SelectOption key={3} value={neverTxt} />,
];
this.options1 = [
<SelectOption key={0} value={hourTxt} />,
<SelectOption key={1} value={weekTxt} />,
<SelectOption key={2} value={dayTxt} isPlaceholder />,
<SelectOption key={3} value={neverTxt} />,
];
this.onToggle = (isOpen) => {
this.setState({
isOpen
});
};
this.onToggle1 = isOpen1 => {
this.setState({
isOpen1
});
};
this.onSelect = (event, selection, isPlaceholder) => {
if (isPlaceholder){
this.clearSelection();
}
else {
this.setState({
selected: selection,
isOpen: false
},() => { this.postSelectData()
});
}
};
this.onSelect1 = (event, selection, isPlaceholder) => {
if (isPlaceholder) this.clearSelection1();
else {
this.setState({
selected1: selection,
isOpen1: false
},() => { this.postSelectData()
});
}
};
this.clearSelection = () => {
this.setState({
selected: null,
isOpen: false
},() => { this.postSelectData()
});
};
this.clearSelection1 = () => {
this.setState({
selected1: null,
isOpen1: false
},() => { this.postSelectData()
});
};
在渲染()下
const {isOpen, selected,isOpen1, selected1} = this.state
在 return() 下
<Select
variant={SelectVariant.single}
onToggle={this.onToggle}
onSelect={this.onSelect}
selections={selected}
isOpen={isOpen}
>
{this.options}
</Select>
<Select
variant={SelectVariant.single}
onToggle={this.onToggle1}
onSelect={this.onSelect1}
selections={selected1}
isOpen={isOpen1}
>
{this.options1}
</Select>