reactjs - 在 React 中提交表单后无法重置输入字段
问题描述
我有一个带有输入字段的表单。提交表单后需要清除输入字段。我试图将状态设置为空数组 - 它没有工作,然后我尝试使用 refs - 对我也不起作用......
此函数激活 onSubmit 事件。
addHaspInfo = (e) => {
// e.preventDefault();
axios.post("/hasp", {
company: {
name: e.target[3].value,
city: e.target[4].value,
phone: e.target[5].value
},
numberOfKeys: e.target[2].value,
serial: e.target[0].value,
soft: e.target[1].value,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
axios.get("/hasp")
.then((haspData) => {
console.log(haspData.data);
this.setState({
hasps: haspData.data
});
});
this.setState({
hasps: [] //this don't reset input fields
});
}
<form id="formId" className="form-group haspAddForm" onSubmit={this.addHaspInfo}>
蚂蚁这也不起作用:
clearInput = () => {
this.setState({hasps: []});
ReactDOM.findDOMNode(this.refs.myInput).focus(); //this don't reset input fields
}
<button onClick={this.clearInput} className="btn btn-primary" type="submit" style={{marginBottom:'40px', marginRight: '110px'}}>Add new hasp info</button>
输入字段之一
<input ref="myInput" type="text" className="form-control" value={this.state.serial} placeholder="00000-00000" required /><br />
解决方案
尝试
clearInput = ()=>{
this.setState({...this.state,
serial: ""
})
}
这是您重置输入字段的方式。在状态中展开,然后将表示输入字段值的状态设置为空字符串。
推荐阅读
- ssl - ActiveMQ:无法通过 Stomp 启用 SSL
- git - git push 失败 - 权限被拒绝(公钥)
- node.js - 找不到NodeJS的功能?
- php - 将单击的按钮(不是表单中的按钮)的变量值传递给ajax url?
- sql - 我需要创建一个字段,它是 maxdate 的第二个日期
- python - Python - 概率
- sql-server - Azure 数据资源管理器 - 用于存储对象属性/配置的解决方案
- azure - 使用其 REST API 将 Azure DevOps 指标导入 Elatic Search 数据库?
- ios - macOS 中的 xcrun 无效的活动开发者路径错误
- python - 使用 pydata_google_auth 时 Python SSL 错误握手错误