如何在提交 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>
`

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

提交时,您将更改状态this.setState({email:'',subject:'',body:''});

但是,文本区域没有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 :''});
        })

我看到您在文本区域上有onChange函数,但是您没有设置文本,因此您的组件不受 react 控制。你应该做这样的事情:

<textarea 
  id={this.props.name} 
  className="materialize-textarea" 
  name={this.props.name} 
  value={this.props.body} 
  onChange={this.props.onChange} 
  placeholder={this.props.body} 
>
  {this.props.body}
</textarea>

这样,当您setState()并重置this.props.body值时,textarea将为空

最新更新