【问题标题】:form is not submitting when some field is empty on using react使用反应时某些字段为空时表单未提交
【发布时间】:2016-06-02 14:21:23
【问题描述】:

我在提交表单时遇到了一些奇怪的故障,其中某些字段为空。这是代码:

...
constructor(props) {
    super(props);
    this.state = {
        form: {
            email: '',
            password: '',
            retype: ''
        }
    };
},
_updateTextbox(type, ev) {
    var oldState = this.state;
    var newFormState = Object.assign({}, this.state.form, {
        [type]: ev.target.value
    });

    this.setState(Object.assign({}, this.state, {
        form: newFormState
    }));
}
_submit(ev) {
    alert('Submit!');
    ev.preventDefault();
},
render (){
    return (
        <form onSubmit={this._submit.bind(this)}>
            <input type="email" onChange={this._updateTextbox.bind(this, 'email')} value={this.state.form.email} />
            <input type="password" onChange={this._updateTextbox.bind(this, 'password')} value={this.state.form.password} />
            <input type="password" onChange={this._updateTextbox.bind(this, 'retype')} value={this.state.form.retype} />

            <button type="submit">Submit</button>
        </form>
    );
}
...

如果我尝试使用所有空字段提交此表单,它会起作用。但是如果我只输入电子邮件字段,表单永远不会提交任何其他字段是否为空。您可以看到我曾经在提交事件时发出警报,但它从未弹出。我不知道为什么会这样。这是某种故障吗?

【问题讨论】:

    标签: javascript forms reactjs


    【解决方案1】:

    您似乎遇到了错误 ev.preventDefault(); },

    编辑完整代码

    import React, { Component } from 'react'
    
    class Example extends Component {
      constructor(props) {
        super(props);
        this.state = {
          form: {
            email: '',
            password: '',
            retype: ''
          }
        };
      }
      _updateTextbox(type, ev) {
        var newFormState = Object.assign({}, this.state.form, {
          [type]: ev.target.value
        });
    
        this.setState(Object.assign({}, this.state, {
          form: newFormState
        }));
      }
      _submit(ev) {
        alert('Submit!');
        ev.preventDefault();
      }
      render (){
        return (
            <form onSubmit={this._submit.bind(this)}>
              <input type="email" onChange={this._updateTextbox.bind(this, 'email')} value={this.state.form.email} />
              <input type="password" onChange={this._updateTextbox.bind(this, 'password')} value={this.state.form.password} />
              <input type="password" onChange={this._updateTextbox.bind(this, 'retype')} value={this.state.form.retype} />
    
              <button type="submit">Submit</button>
            </form>
        );
      }
    }
    
    export default Example
    

    capture

    【讨论】:

    • 不,没关系,上面的代码只是我写的解释。仍然无法正常工作:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多