获取event.preventDefault();不是一个功能。为什么它不是一个功能?

时间:2016-11-21 16:14:57

标签: javascript reactjs

我正在使用react并遵循一些表单提交的教程,我在我的控制台中遇到了这个问题:

contact.js:67 Uncaught TypeError: event.preventDefault is not a function(…)

这是我的代码:

contact.js

class ContactForm extends Component {


  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = { open: false };
  }

  handleSubmit(event) {
    console.log('hello');
    event.preventDefault();
  }

  handleTouchTap = () => {
    this.setState({ open: true });
  }

  handleRequestClose = () => {
    this.setState({ open: false });
  }

  render() {
    return(
      <div>
        <Paper className="Form" zDepth={2}>
          <Formsy.Form onSubmit={this.handleSubmit}>
            <FormsyText
              name="Enter Name"
              floatingLabelText="Enter your name"
            />
            <FormsyText
              name="Enter email address"
              floatingLabelText="Enter your email address"
            />
            <FormsyText
              name="message"
              floatingLabelText="What can I do for you?"
            />
            <RaisedButton onTouchTap={this.handleTouchTap}
               type="submit"
               label="Submit your message"
               primary={true}
            />
            <Snackbar
              open={this.state.open}
              message="Thank your for submitting your message. I'll get back to you as soon as I can!"
              autoHideDuration={2000}
              onRequestClose={this.handleRequestClose}
            />
          </Formsy.Form>
        </Paper>
      </div>
    );
  }
}

export { ContactForm };

正如您在我的代码和我可以看到的内容中所看到的,我已将handleSubmit正确绑定到ContactForm并应在onSubmit处理程序上正确调用它与this.handleSubmit。我在这里可以缺少什么?

2 个答案:

答案 0 :(得分:3)

您没有使用默认表单...

这是公式

来自文档

https://github.com/christianalfoni/formsy-react/blob/master/API.md#onsubmit

  

onSubmit(data,resetForm,invalidateForm)

     

采取一个   单击提交按钮时运行的函数。

     

第一个参数是表单的数据。第二个论点是   重置表单。第三个参数将使表单无效   映射到输入的对象。这对服务器端很有用   验证。例如。 {email:“此电子邮件已被删除”}。重置或   使表单无效将导致setState在表单元素上运行   成分

答案 1 :(得分:0)

Formsy将表单数据作为第一个参数传递给submit事件处理程序。 此表单数据没有函数preventDefault()

如果您参考提交机制的内部实现,您将看到默认情况下始终调用preventDefault()

submit: function (event) {

  event && event.preventDefault();

  // Trigger form as not pristine.
  // If any inputs have not been touched yet this will make them dirty
  // so validation becomes visible (if based on isPristine)
  this.setFormPristine(false);
  var model = this.getModel();
  this.props.onSubmit(model, this.resetModel, this.updateInputsWithError);
  this.state.isValid ? this.props.onValidSubmit(model, this.resetModel, this.updateInputsWithError) : this.props.onInvalidSubmit(model, this.resetModel, this.updateInputsWithError);

},

Source

相关问题