首页 > 解决方案 > 提交 React JS 后如何删除文本区域内的文本

问题描述

提交后无法删除文本区域内的文本

我试过 setState() 但它不会删除它只删除值的文本

   handleSubmit(evt){
        evt.preventDefault();
        console.log(this.state);
        // const data = {
        //   email:this.state.email,
        //   subject:this.state.subject,
        //   body:this.state.body,
        // }
        const url = 'http://localhost:5000/api/nodemailer';
         axios.post( url, this.state)
        .then((res)=> {
          console.log(res);
          this.setState({email:'',subject:'',body:''});
        })
        .catch(err => {console.log('not sent'+err)});          




  `
   <div className="row">
            <div className="input-field col s12">
            <i className="material-icons prefix">mode_edit</i>
              <textarea id={this.props.name} className="materialize-textarea" name={this.props.name} value={this.props.body} onChange={this.props.onChange} placeholder={this.props.body} ></textarea>
              <label htmlFor={this.props.name}>{this.props.title}</label>
            </div>
          </div>
`

预期的结果是提交后看到字段值为空但我得到的结果是文本区域仍然有文本但值为空

标签: reactjsforms

解决方案


当你提交时,你改变了状态this.setState({email:'',subject:'',body:''});

但是,textarea 没有,value= this.state.body而是有value={this.props.body}

所以试试这个:

<div className="row">
   <div className="input-field col s12">
        <i className="material-icons prefix">mode_edit</i>
         <textarea id={this.props.name} className="materialize-textarea" name={this.props.name} value={this.state.bodyState} onChange={this.props.onChange}      placeholder={this.state.bodyState} ></textarea>
         <label htmlFor={this.props.name}>{this.props.title}</label>
      </div>
  </div>




this.setState({bodyState = this.props.value)};

const url = 'http://localhost:5000/api/nodemailer';
         axios.post( url, this.state)
        .then((res)=> {
          console.log(res);
          this.setState({bodyState :''});
        })

推荐阅读