[英]How to get the values for dynamically generated input field in react js?
Hii I am new to React Js, After selecting count InputCount
, I had generated input fields dynamically.Now I want to get the value for the inputs field and also I want to validate all the fields. InputCount
,我是 React Js 的InputCount
,选择 count InputCount
,我动态生成了输入字段。现在我想获取输入字段的值,并且我想验证所有字段。
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.onChangeCount = this.onChangeCount.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {,
InputCount: "",
}
}
onChangeCount(e) {
this.setState({
InputCount: e.target.value,
})
}
render() {
let options1 = []
for (let j = 0; j <= this.state.InputCount; j += 1) { options1.push(j); }
return (
{this.state.InputCount && (
options1.map((i) => {
return (<div>
<input type="text" name="name" placeholder="Name" /><br />
<input type="text" name="name" placeholder="RollNumber" />
</div>)
})
)}
please help me to get value from the input fields and also validate the form.请帮助我从输入字段中获取价值并验证表单。
Name input field unique by combining with the loop index.通过与循环索引组合来命名输入字段是唯一的。
And don't forget to use key
when map
item.并且不要忘记在map
项目时使用key
。
class App extends React.Component { constructor(props) { super(props); this.onChangeCount = this.onChangeCount.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { InputCount: 2, } } onChangeCount(e) { this.setState({InputCount: e.target.value }) } handleChange = (e) => { console.log('name: ', e.target.name, ' value:', e.target.value) // Do what you want here } render() { let options1 = [] for (let j = 0; j <= this.state.InputCount; j += 1) { options1.push(j) } return ( <div> {options1.map((i) => { return ( <div key={`group-input-${i}`}> <input onChange={this.handleChange} type="text" name={`${i}-name`} placeholder="Name" /><br /> <input onChange={this.handleChange} type="text" name={`${i}-rollNumber`} placeholder="RollNumber" /> </div> )})} </div> )}}
Now I want to get the value for the inputs field现在我想获取输入字段的值
To address each field separately, you need to name all of them uniquely.要分别寻址每个字段,您需要唯一地命名所有字段。 So your JSX for the fields needs to have a distinct name
attribute for each field:因此,字段的 JSX 需要为每个字段具有不同的name
属性:
options1.map((i) => {
return (<div>
<input type="text" name="name-{ i }" placeholder="Name" /><br />
<input type="text" name="rollnumber-{ i }" placeholder="RollNumber" />
</div>)
})
Now each input
element will have a name
attribute unique for that element.现在,每个input
元素都将具有该元素唯一的name
属性。 Assuming options1
contains values 0 through 2:假设options1
包含值 0 到 2:
You will get the values for the field by interrogating the field by its name
attribute .您将通过查询字段的name
属性来获取该字段的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.