我在表单中有两个字段,但我无法将数据发布到服务器。我知道如何提交单个文件但如何在表单中提交多个字段。 下面是2个字段的代码
class Createstudent extends React.Component {
constructor(props) {
super(props);
this.state = {name: '',
age:''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({name: event.target.value});
this.setState({age:event.target.value});
}
handleSubmit(event) {
alert(this.state.name);
axios.post('/create',{values:this.state.name,ages:this.state.age})
.then(function(response){
console.log(response);
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={this.handleChange} />
</label>
<label>
Age:
<input type="text" value={this.state.age} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
答案 0 :(得分:0)
原因是你要更新具有相同值的fields
,更改任何一个,更新特定字段,它会起作用,试试这个:
handleChange(event) {
if(event.target.name == 'name')
this.setState({name: event.target.value});
else
this.setState({age: event.target.value});
}
或
handleChange(event) {
this.setState({[event.target.name]: event.target.value});
}
将name
attr添加到input
字段以唯一标识它们,使用此render
方法:
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name='name' value={this.state.name} onChange={this.handleChange} />
</label>
<label>
Age:
<input type="text" name='age' value={this.state.age} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
检查jsfiddle
:https://jsfiddle.net/dp0an79f/
答案 1 :(得分:0)
我已经改变了这样的代码。它的工作原理。
import React from 'react';
import axios from 'axios';
class Createstudent extends React.Component {
constructor(props) {
super(props);
this.state = {name: '',
age:''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
alert(this.state.name);
axios.post('/create',{values:this.state.name,ages:this.state.age})
.then(function(response){
console.log(response);
})
}
componentDidMount(){
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
</label>
<label>
Age:
<input type="text" value={this.state.age} onChange={e => this.setState({ age: e.target.value })} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}