我正在使用受控输入进行反应表单来访问表单输入上的更改。它包含很多字段,但我没有发布所有字段。
import React from 'react';
import Links from './Links.jsx';
import axios from 'axios';
import Dialog from 'react-bootstrap-dialog';
import {Typeahead} from 'react-bootstrap-typeahead';
import Autocomplete from 'react-autocomplete';
import style from './app.css';
class AddNewEmployee extends React.Component {
constructor(props){
super(props);
this.state = {
firstName : '',
middleName : ''
}
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(){
const name = e.target.name;
const value = e.target.value;
this.setState({
[name]: value
})
}
render() {
return(
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="firstName"
value={this.state.firstName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="middleName"
value={this.state.middleName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
)
}
}
export default AddNewEmployee;
上面的代码到目前为止工作正常,但我要求保留一个嵌套对象来保存表单输入值。
但我在这里遗漏了一些如何处理表单元素上的用户输入的事情。 当我们有一个嵌套对象时,我们如何处理用户输入。
import React from 'react';
import Links from './Links.jsx';
import axios from 'axios';
import Dialog from 'react-bootstrap-dialog';
import {Typeahead} from 'react-bootstrap-typeahead';
import Autocomplete from 'react-autocomplete';
import style from './app.css';
class AddNewEmployee extends React.Component {
constructor(props){
super(props);
this.state = {
employee : {
firstName : '',
middleName : ''
}
}
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(){
// here how to handle those input changes
}
render() {
return(
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="firstName"
value={this.state.employee.firstName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="middleName"
value={this.state.employee.middleName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
)
}
}
export default AddNewEmployee;
答案 0 :(得分:1)
handleUserInput(e) {
// Option #1 (mutable data)
let {employee} = this.state;
const name = e.target.name;
const value = e.target.value;
employee[name] = value;
this.setState({
employee
});
// Option #2 (immutable data)
const { employee } = this.state;
const name = e.target.name;
const value = e.target.value;
this.setState({
employee: {
...employee,
[name] : value
}
});
}
此外,由于您在构造函数中绑定handleUserInput
,因此可以将onChange={(event) => this.handleUserInput(event)}
简化为onChange={this.handleUserInput}