简体   繁体   English

在 React 中迭代表单元素数组

[英]Iterating over form elements array in React

I have a React functional component with a form, onSubmit I want to loop through all form elements....我有一个带有表单的 React 功能组件,onSubmit 我想遍历所有表单元素....

export default function TransactionFilter() {

return (
   <form onSubmit={handleSubmit}>
      <TextField id="username" /><br/>
      <TextField id="password" /><br/>
   </form>
)

const handleSubmit = (event) => {
        event.preventDefault();
        var formElements = event.target.elements

        formElements.forEach(element => 
          console.log(`I found this ${element}`)
        );

But this code is giving me an error...但是这段代码给了我一个错误......

react-dom.development.js:476 Uncaught TypeError: formElements.forEach is not a function
    at handleSubmit (FilterForm.js:49)
    at HTMLUnknownElement.callCallback (react-dom.development.js:337)

Am I not using forEach in the right way?我没有以正确的方式使用forEach吗? If not, then what is the correct way to iterate over form elements array in React ?如果不是,那么在 React 中迭代表单元素数组的正确方法是什么?

The elements object is actually a HTMLFormControlsCollection object.元素对象实际上是一个HTMLFormControlsCollection对象。

You can use the Array.prototype.forEach method to iterate the collection like this:您可以使用Array.prototype.forEach方法来迭代集合,如下所示:

Array.prototype.forEach.call(event.target.elements, (element) => {
  console.log(element);
})

event.target.elements will return undefined event.target.elements将返回 undefined

I suggest doing it in react way, have an array of all form elements in state.我建议以反应方式进行操作,将所有表单元素的数组置于状态。

 export default function TransactionFilter() {
  const [formData, setFormData] = React.useState([
    { id: 'username', value:'' },
    { id: 'password', value:'' }
  ]);
  const handleSubmit = (event) => {
    event.preventDefault();
    formData.forEach(element => 
      console.log(`I found this ${element.value}`)
    );
  };
  return (
       <form onSubmit={handleSubmit}>
          {formData.map((element, index) => {
            return ( <React.Fragment>
                     <TextField id={element.id} value={element.value} 
                     onChange={e => {
                       setFormData(
                         [
                           ...formData.slice(0, index), 
                           { ...formData[index], value: e.target.value },
                           ...formData.slice(index + 1)
                         ]
                       );
                     }}

                     />
                     <br/>
                   </React.Fragment>
            );
          })}
       </form>
  );
}

You can also use the of syntax:您还可以使用of语法:

const handleSubmit = event => {
    event.preventDefault()

    for (const element of event.target.elements) {
        console.log(`I found this ${element}`)
    }
}

    
   

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

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