[英]How to add a new textfield on button click and add integer value of that input field to an array in react
I want to add a new input field on button click and add the integer value of that input field to an array in react我想在按钮单击时添加一个新的输入字段,并将该输入字段的 integer 值添加到反应数组中
const [price, setPrice] = useState([])
const [count, setCount] = useState([1])
const addNewTextField = () => setCount(prev => [...prev,1])
const addInputValue= () => {
setPrice()
console.log(price)
}
<Button onClick={addNewTextField}>Add TextField</Button >
{
count.map((item, i) => {
return (
<TextField key={i} value={item.value} id={i} type='text' />
)
})
}
<Button onClick={addInputValue}>submit</Button >
first input value is 100, second input value is 200, result should be like this when I add new input field: [100,200]
第一个输入值为 100,第二个输入值为 200,当我添加新输入字段时,结果应该是这样的: [100,200]
Try like below.尝试如下。 You can keep only price
state.您只能保留price
state。
import { useState } from "react";
const App = () => {
const [price, setPrice] = useState([""]);
const addNewTextField = () => setPrice((prev) => [...prev, ""]);
const addInputValue = (i, newValue) => {
console.log(i, newValue);
setPrice((prevState) =>
prevState.map((value, valueIndex) =>
valueIndex === i ? newValue : value
)
);
};
console.log(price);
return (
<>
<button onClick={addNewTextField}>Add TextField</button>;
{price.map((item, i) => {
return (
<input
key={i}
placeholder={`input ${i}`}
// value={item}
id={i}
type="text"
onChange={(e) => addInputValue(i, e.target.value)}
/>
);
})}
<button onClick={addInputValue}>submit</button>
</>
);
};
export default App;
const [price, setPrice] = useState([]);
const [count, setCount] = useState([1]);
const [value, setValue] = useState("");
const addNewTextField = () => setCount(prev => [...prev,prev + 1]);
const addInputValue= () => {
setPrice(price.concat(value));
console.log(price)
}
<Button onClick={addNewTextField}>Add TextField</Button >
{
count.map((item, i) => {
return (
<TextField key={i} value={value} id={i} type='text' onChange={e => setValue(e.target.value)} />
)
})
}
<Button onClick={addInputValue}>submit</Button >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.