【问题标题】:Clear reactJs textarea after submit提交后清除reactJs textarea
【发布时间】:2015-09-12 03:18:40
【问题描述】:

我在天窗对话框中有以下表单组件,提交后,如果重新打开包含表单的对话框,它包含之前提交的值。谁能告诉我如何在每次打开对话框时停止此操作并清除 textarea 值?

这是我的组件:

var AddNoteForm = React.createClass({


componentDidMount: function() {

        React.findDOMNode(this.refs.notes).value = "";
},
handleSubmit: function (event) {
    event.preventDefault();

    var notes = React.findDOMNode(this.refs.notes).value;

    var details = {
        studentId: this.props.studentId,
        schoolId: this.props.schoolId,
        notes: notes
    };

    this.props.onSubmit(details);
},

render: function() {
    return (
        <form className="pure-form pure-form-aligned"
            onSubmit={this.handleSubmit}>
            <div className="pure-control-group">
                <label htmlFor="notes">Note</label>
                <textarea ref="notes" id="notes" placeholder="Note..." >
                </textarea>

            </div>
            <div className="pure-controls">
                <input type="submit" value="Save" />
            </div>
        </form>
    );
}
});

module.exports = AddNoteForm;

【问题讨论】:

    标签: javascript forms textarea reactjs


    【解决方案1】:

    基本上你的表单没有被卸载。所以在 componentDidMount 中写代码是没有意义的。因此,解决问题的快速方法是在读取处理提交方法中的值后清除 textarea 框

    handleSubmit: function (event) {
      event.preventDefault();
    
      var notes = this.refs.notes;
    
      var details = {
        studentId: this.props.studentId,
        schoolId: this.props.schoolId,
        notes: notes.value
      };
    
      notes.value = ""; // Unset the value
      this.props.onSubmit(details);
    },
    

    【讨论】:

    • 感谢您的回复。我已经尝试过了,但是对话框中的值仍然存在,有什么想法吗?
    【解决方案2】:

    所以如果有人陷入这个问题, 我使用的是不受控制的组件,清除它有点复杂, 我只是换了一个受控的然后得到它:)

    <form onSubmit={e => this.handleSubmit(e)}>
    <textarea value={this.state.text} onChange={ e => this.handleChange(e) } />
    <button>Submit Comment</button>
    </form>
    

    防止默认很重要

      handleSubmit = event => {
      event.preventDefault();    
      this.setState({ text: '' });
      };
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多