[英]how to get last value from user input event and push into array react.js
我有一个 Input 组件,它根据 JSON 数据创建尽可能多的输入标签。
我在输入标签中使用 onChange 方法,并使用 contextAPI 将事件传递到 function “handleChange”,以记录不同组件中的值。
我试图然后将该值推送到一个数组中,但是这样做时它会推送用户按下的每个事件假设用户输入 450,当推送数组时它会显示为 ["4", "45", "450] ,我将如何获得用户放置的最后一个值?
输入组件:
const { handleChange } = useContext(FormContext);
return (
<input
id={`input-text${id}`}
onChange={(e) => handleChange(id, e)}
style={{
position: "absolute",
top: `${fieldsPosX}px`,
left: `${fieldsPosY}px`,
background: "blue",
border: "black",
height: "30px",
maxWidth: "70px",
width: "100%",
zIndex: "40",
color: "#fff",
textAlign: "center"
}}
maxLength={maxLength}
type={"text"}
/>
);
}
export default Input;
手柄更改 function:
const handleChange = (id, e) => {
console.log(e.target.value);
answers.push(e?.target?.value);
};
当前 output: ["4", "45", "450"]
预期 output: ["450"]
也许您可以使用提交<button>
作为触发器来将用户输入推送到数组,而不仅仅是使用<input>
。 onChange
事件跟踪<input>
中的每个更改,因此那里的每个更改都会触发handleChange()
function。 这就是为什么每次用户输入一个字符时都会触发handleChange()
function。
[answers, e?.target?.value]
使用它而不是 answers.push
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.