React中表单提交错误

时间:2017-07-07 10:56:33

标签: javascript forms reactjs meteor

我在Meteor React应用程序中遇到了这个问题。

长话短说:我有一个表单来创建一个事件,我想要handleSubmit()来处理错误消息,如果没有,则向db添加事件。我确实导入了{Events},实际上在我做了一些更改之前表单已经工作了。当我运行它时,我收到一条错误消息:Uncaught TypeError:event.target [matches]不是一个函数。不幸的是,抛出错误的文件给我带来了胡言乱语。

这是我的代码:

export default class Create extends React.Component {
constructor(props) {
  super(props);
  this.state = {
      error: {}
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
  evt.preventDefault();

  this.setState({error: {}});
  let title = this.refs.title.value;
  if (!title) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.title = 'Title has to be filled up.';
      return newState;
    })
  }
  let description = this.refs.description.value;
  if (!description) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.description = 'Description has to be filled up.';
      return newState;
 })
}

if (!this.state.error) {
   Events.insert({title: title, description: description});
   this.props.history.push('/home');
}

和我的HTML:

    <form onSubmit={this.handleSubmit} noValidate>

        <input ref="title" type="text" name="title" placeholder="Title"
        style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.title}</div>

        <input ref="description" type="text" name="description" placeholder="Description"
        style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.description}</div>

        <button type="submit" className="btn btn-success">Create new event</button>

    </form>

不幸的是,在此错误得到解决之前我无法继续执行该项目,所以如果有人帮助我,我会很高兴!

最佳,

1 个答案:

答案 0 :(得分:0)

您的目标元素

似乎不支持element.matches函数

我不清楚这是否是由流星本机脚本引起的,因为我没有使用流星。

但是,您可以通过添加此代码并添加自己的原型来检查此问题,以绕过此错误。

if (!Element.prototype.matches) {
Element.prototype.matches = 
    Element.prototype.matchesSelector || 
    Element.prototype.mozMatchesSelector ||
    Element.prototype.msMatchesSelector || 
    Element.prototype.oMatchesSelector || 
    Element.prototype.webkitMatchesSelector ||
    function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i = matches.length;
        while (--i >= 0 && matches.item(i) !== this) {}
        return i > -1;            
    };
}

SOURCES

我希望这可以解决您的问题。