首页 > 解决方案 > 在 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 />

标签: reactjsapiaxios

解决方案


尝试

clearInput = ()=>{
  this.setState({...this.state,
                  serial: ""
                })
  }

这是您重置输入字段的方式。在状态中展开,然后将表示输入字段值的状态设置为空字符串。


推荐阅读