【发布时间】:2021-11-23 10:06:35
【问题描述】:
我试图实现一个带有输入框的表单,允许用户在单击按钮时添加/删除文本输入组件,这是我目前所拥有的,
const UserInput = () => {
const selectValues = ['Value 1', 'Value 2'];
const [textBox, setTextBox] = useState(selectValues);
const addNewTextInput = () => {
const newTextValue = 'Value' + textBox.length;
setTextBox([...textBox, newTextValue])
};
const removeInput = (index: number) => {
const textInput = [...textBox];
textInput.splice(index, 1);
setTextBox(textInput);
};
return (
<div>
<button onClick={addInput}>+</button>
<button onClick={removeInput}>+</button>
{textBox.map((value, i) => {
return (
<input
onChange={handleChange}
value={value}
id={i}
type={type}
/>
);
</div>
})}
)
}
现在,我可以添加一个新的文本输入并成功删除该输入,但是当我删除时,不是最近添加的输入,而是第一个输入字段被删除。我不确定 removeInput 函数是否有任何问题。另外,我在不同的文件中声明了 handleChange 函数。
【问题讨论】:
标签: javascript reactjs