我正在尝试将表单内输入的值调用到我的获取函数,但它无法读取它,请帮助我。我打算做一个获取帖子,这样我就可以将它插入到我的表格中。
我的功能是这样的:
handleSubmit() {
debugger
function createNewProfile(profile) {
const formData = new FormData();
formData.append('Employee_Name', profile.Employee_Name);
formData.append('Address', profile.Address);
formData.append('Department', profile.Department);
return fetch('http://localhost:5118/api/employeedetails/PostEmployeeDetail/', {
method: 'POST',
body: formData
}).then(response => response.json())
}
createNewProfile(profile)
.then((json) => {
// handle success
}
).catch(error => error);
}
这是我想要的表格
<form onSubmit={this.handleSubmit}>
<div className="container">
<div className="modal-body">
<table>
<tbody>
<tr>
<td>Name</td>
<td>
<input type="text"
name="Employee_Name"
className="EmployeeDetails"
value={this.props.Employee_Name}/>
</td>
</tr>
<tr>
<td>Address</td>
<td>
<input type="text"
name="Address"
className="EmployeeDetails"
value={this.props.Address}
onChange={this.props.handleChange}/>
</td>
</tr>
<tr>
<td>Department</td>
<td>
<input type="text"
name={this.props.Department}
className="EmployeeDetails"
value={this.props.Department}/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="modal-footer">
<input type="submit" className="btn btn-info" onClick={ this.handleSubmit} value=" Add Employee"/>
<button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
您正在从父组件控制表单值,所以我建议您也从父组件传递一个提交函数和提交的onClick,在父组件中进行api调用。
如果在父组件中进行 api 调用,则需要通过
this.state.key
来访问值;如果在子组件中进行 api 调用,则需要使用 this.props.key
来访问值。
注意:我假设您正在根据子组件的更改更新父组件中的输入值,因为您从父组件传递了 onChange 函数。
子组件中的Api调用:
handleSubmit(){
let profile = this.props;
const formData = new FormData();
formData.append('Employee_Name', profile.Employee_Name);
formData.append('Address', profile.Address);
formData.append('Department', profile.Department);
fetch('http://localhost:5118/api/employeedetails/PostEmployeeDetail/', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(response => {
//handle success
})
}
父组件中的Api调用:
handleSubmit(){
let profile = this.state;
const formData = new FormData();
formData.append('Employee_Name', profile.Employee_Name);
formData.append('Address', profile.Address);
formData.append('Department', profile.Department);
fetch('http://localhost:5118/api/employeedetails/PostEmployeeDetail/', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(response => {
//handle success
})
}
更新:
需要在构造函数中绑定
handleSubmit
函数,构造函数的写法如下:
constructor(){
super();
this.state = {};
this.handleSubmit = this.handleSubmit.bind(this)
}