简体   繁体   English

输入字段动态映射但无法从所有字段 React JS 获取输入值

[英]Input field mapped dynamically but failed to get input values from all the fields React JS

I have 4-5 input fields mapped as per response.我根据响应映射了 4-5 个输入字段。 The user needs to enter value in each field but when I try to fetch the final value from all fields it gives me value of only the last input field.用户需要在每个字段中输入值,但是当我尝试从所有字段中获取最终值时,它只给了我最后一个输入字段的值。 I would like to have values in an array which I can later join.我想在一个数组中有值,以后可以加入。 There's one handler function for onChange.有一个处理程序 function 用于 onChange。 I have tried using spread operator but doesn't help.我试过使用传播运算符,但没有帮助。

const [inputValue, setInputValue] = useState({});
const handleChange = (value,name,i)=>{
 setInputValue({ ...inputValue, [name]: value })
}

records.map((record, i) => {
              return (
                <>
                    <input
                      onChange={(e) =>
                        handleChange(e.target.value, e.target.name, i)
                      }
                      name={record.title}
                      key={i}
                      value={record.value}
                 
                    />
                  </label>
                </>
              );
            })

You can use built in Form tag for that matter:您可以为此使用内置的 Form 标签:

<form onSubmit={submitHandlerFunction}>
 {fields.map(field => (
  <input key={field.name} name={field.name}/>
  )}
 <button type="submit">Submit</button>
</form>

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

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