问题
如何让一个数据跟着另一个数据联动起来, 比如修改一个下拉框, 一个下拉框的内容也能一起改变
实现
可以借助Map来实现这个功能
- 把下拉框的option写成Map的value
- 当前更改的数据当做源数据, 另一个跟随改变的数据是目标数据
- 源数据在Map里的key为
source
目标数据在Map里的key为当前的源数据的值
那么我们可以得出些一个对应下拉框内容的Map
export const OPTIONS = new Map([
[
'source',
[
{
value: 'fruit',
label: '水果',
},
{
value: 'vegetable',
label: '蔬菜',
},
],
],
[
'fruit',
[
{
value: 'apple',
label: '水果',
},
{
value: 'orange',
label: '橘子',
},
],
],
[
'vegetable',
[
{
value: 'cabbage',
label: '白菜',
},
{
value: 'carrot',
label: '胡萝卜',
},
],
],
])
const [state, setState] = useState({
source: '',
target: ''
})
const sourceOption = OPTIONS.get('source')
const targetOption = OPTIONS.get(state.source)
<>
<Select value={state.source}>
{sourceOption.map((item) => (
<Select.Option key={item.value} value={item.value}>
{item.label}
</Select.Option>
))}
</Select>
<Select value={state.target}>
{targetOption.map((item) => (
<Select.Option key={item.value} value={item.value}>
{item.label}
</Select.Option>
))}
</Select>
<>