问题:
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 val...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
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.
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.
回答1:
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:
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. Assuming options1
contains values 0 through 2:
- name-0
- rollnumber-0
- name-1
- rollnumber-1
- name-2
- rollnumber-2
You will get the values for the field by interrogating the field by its name
attribute.
回答2:
Name input field unique by combining with the loop index.
And don't forget to use key
when map
item.
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>
)}}