需求:展示四个选择框,当第一个选择框选择了数据A后,剩下三个选择框的下拉数据内不展示数据A,第二、三、四,同理;
<div className={styles.selectStyle}>
{indicators.map((item, index) => {
return (
<div key={item.type}>
<Select
value={optionSelectList[item.name]}
style={{ width: 120 }}
options={getOptions(item.name)}
onChange={(value)=>{
const newValue = {...optionSelectList};
newValue[item.name] = value;
setOptionSelectList(newValue);
}}
/>
{index === indicators.length - 1 ? (
''
) : (
<span className={styles.selectText}>对比</span>
)}
</div>
);
})}
</div>
const types = [
{
label: '消耗',
value: '消耗',
},
{
label: '展示量',
value: '展示量',
},
{
label: '千次展示成本',
value: '千次展示成本',
},
{
label: '点击量',
value: '点击量',
},
{
label: '单次点击成本',
value: '单次点击成本',
},
{
label: '点击率',
value: '点击率',
},
{
label: '转化量',
value: '转化量',
},
{
label: '转化成本',
value: '转化成本',
},
{
label: '转化率',
value: '转化率',
},
]; // 下拉选项
const indicators: [
{
type: 0,
name: 'theOne',
},
{
type: 1,
name: 'theTwo',
},
{
type: 6,
name: 'theThree',
},
{
type: 7,
name: 'theFour',
},
];
const [optionSelectList, setOptionSelectList] = useState({
theOne: '消耗',
theTwo: '展示量',
theThree: '转化量',
theFour: '转化量',
}); // 四个单选框默认选择的值
// name是选择框的名字,这个函数返回的是当前选择框的最新下拉数据
const getOptions = (name: string) => {
const selectValueList = [];
for (const key in optionSelectList) {
if (key !== name) {
selectValueList.push(optionSelectList[key]);
}
}
const newListChild = types.filter((item) => {
return selectValueList.indexOf(item.value) === -1;
});
return newListChild;
};
原理是setValue的时候会重新运行一遍getOptions函数,这样,任何一个选择框的值发生变化的时候其余三个选择框的下拉数据都会发生相应的改变;