每次选择之一的值发生变化时,您都可以收集选项。仅在重新选择主时(setSize
重置时color
和重置material
时)完成依赖选择的重置。setColor
material
代码沙盒
const products = [
{ size: "small", color: "red", material: "metal" },
{ size: "small", color: "red", material: "wood" },
{ size: "medium", color: "blue", material: "plastic" },
{ size: "large", color: "blue", material: "metal" },
{ size: "large", color: "yellow", material: "wood" }
];
export default function App() {
const [size, setSize] = React.useState();
const [color, setColor] = React.useState();
const [material, setMaterial] = React.useState();
const sizeOptions = products
.map((p) => p.size)
.filter((v, i, a) => a.indexOf(v) === i)
.map((size) => ({ label: size, value: size }));
const colorOptions = products
.filter((p) => size && p.size === size.value)
.map((p) => p.color)
.filter((v, i, a) => a.indexOf(v) === i)
.map((color) => ({ label: color, value: color }));
const materialOptions = products
.filter(
(p) => size && p.size === size.value && color && p.color === color.value
)
.map((p) => p.material)
.filter((v, i, a) => a.indexOf(v) === i)
.map((material) => ({ label: material, value: material }));
return (
<div className="App">
<Select value={size} onChange={setSize} options={sizeOptions} />
<Select
value={color}
onChange={setColor}
options={colorOptions}
isDisabled={!size}
/>
<Select
value={material}
onChange={setMaterial}
options={materialOptions}
isDisabled={!color}
/>
</div>
);
}