简体   繁体   English

如何从用户输入事件中获取最后一个值并推送到数组 react.js

[英]how to get last value from user input event and push into array react.js

I have an Input component that creates as many input tags as needed based on JSON data.我有一个 Input 组件,它根据 JSON 数据创建尽可能多的输入标签。

I'm using the onChange method in the input tag and passing the event into a function "handleChange" using contextAPI to record the values in a different component.我在输入标签中使用 onChange 方法,并使用 contextAPI 将事件传递到 function “handleChange”,以记录不同组件中的值。

I'm trying to then push that value into an array but when doing so it pushes every event the user presses let's say the user types in 450, when pushing array it comes out as ["4", "45", "450], how would I get the last value user puts?我试图然后将该值推送到一个数组中,但是这样做时它会推送用户按下的每个事件假设用户输入 450,当推送数组时它会显示为 ["4", "45", "450] ,我将如何获得用户放置的最后一个值?

Input component:输入组件:

  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;

handleChange function:手柄更改 function:

  const handleChange = (id, e) => {
    console.log(e.target.value);

    answers.push(e?.target?.value);
  };

Current output: ["4", "45", "450"]当前 output: ["4", "45", "450"]

Expected output: ["450"]预期 output: ["450"]

Maybe you can use a submit <button> as a trigger to push your user input to the array instead of just using the <input> .也许您可以使用提交<button>作为触发器来将用户输入推送到数组,而不仅仅是使用<input> The onChange event track every change in the <input> , so every single change in there will trigger the handleChange() function. onChange事件跟踪<input>中的每个更改,因此那里的每个更改都会触发handleChange() function。 That's why everytime the user input a character it will trigger the handleChange() function.这就是为什么每次用户输入一个字符时都会触发handleChange() function。

[answers, e?.target?.value] 

use this instead of answers.push使用它而不是 answers.push

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM