我对React非常陌生,我以前也做过react本机的工作,所以我非常熟悉一个框架。基本上,我有一个对象数组,比方说在包含5个项。我根据对象的数量填充视图,所以如果有5个对象,我的map函数将填充5个和5个输入。我的问题是如何获得每个输入的值?这是我的代码:
array.map(map((item, index) => (
<h1> item.title </h1>
<input value={input from user} />
)发布于 2019-08-07 09:57:02
一个快速的解决方案是对所有输入值使用一个数组。
const Inputs = ({array}) => {
const [inputs, setInputs] = useState([]);
const setInputAtIndex = (value, index) => {
const nextInputs = [...inputs]; // this can be expensive
nextInputs.splice(index, 1, value);
setInputs(nextInputs);
}
return (
...
array.map((item, index) => (
<div key={index}>
<h1>{item.title}</h1>
<input
value={inputs[index]}
onChange={({target: {value}) => setInputAtIndex(value, index)}
/>
</div>
)
...
);
}请记住,在本例中,每次更改输入时,inputs状态数组都会被[...inputs]复制。如果数组包含许多项,则这是性能问题。
https://stackoverflow.com/questions/57391092
复制相似问题