[英]Capture individual select drop-down values when data is nested inside an array
当它们嵌套在数组中时,我无法选择/捕获单个选择选项。 现在,当在任何数组元素中单击一个选择选项时,所有选项都将更改为该值。
现在我的设置非常标准,适用于单个下拉选择输入。 我不确定如何解决这个问题。
这是我的设置:
const array = [
{ thing: "itemone", thingArr: [1, 2, 3, 4] },
{ thing: "itemtwo", thingArr: [1, 2, 3, 4] },
{ thing: "itemthree", thingArr: [1, 2, 3, 4] },
{ thing: "itemfour", thingArr: [1, 2, 3, 4] }
];
function App() {
const [quantity, setQuantity] = useState(1);
const onSelectChange = e => {
setQuantity(e.target.value);
};
return (
<div className="App">
{array.map(item => (
<div key={item.thing}>
<p>{item.thing}</p>
<select value={quantity} onChange={onSelectChange}>
{item.thingArr.map(option => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</div>
))}
</div>
);
}
同样,我只希望点击的选项更改; 现在,当点击任何给定的选项时,它们都会改变。
您必须为每件事物(下拉列表)存储所选项目。
以下是工作组件的代码段:
const array = [
{thing: 'itemone', thingArr: [1, 2, 3, 4]},
{thing: 'itemtwo', thingArr: [1, 2, 3, 4]},
{thing: 'itemthree', thingArr: [1, 2, 3, 4]},
{thing: 'itemfour', thingArr: [1, 2, 3, 4]},
]
function App() {
const [selectedItems, updateQuantities] = useState({})
const onSelectChange = thing => e => {
updateQuantities({
...selectedItems,
[thing]: e.target.value
})
}
return (
<div className="App">
{array.map(item => (
<div key={item.thing}>
<p>{item.thing}</p>
<select value={selectedItems[item.thing]} onChange={onSelectChange(item.thing)}>
{item.thingArr.map(option => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</div>
))}
</div>
)
}
您可以在https://codesandbox.io/s/react-codesandbox-ge41g上找到相同的代码
更新: onSelectChange箭头函数的另一个实现
const onSelectChange = (thing, e) => {
updateQuantities({
...selectedItems,
[thing]: e.target.value
})
}
...
return (
...
<select value={selectedItems[item.thing]} onChange={(e) => onSelectChange(item.thing, e)}>
...
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.