【问题标题】:error on form submit in React [duplicate]React中的表单提交错误[重复]
【发布时间】:2023-04-01 23:09:01
【问题描述】:

我正在为 Meteor React 应用程序中的这个错误而苦苦挣扎。

长话短说:我有一个创建事件的表单,我希望 handleSubmit() 处理错误消息,如果没有,则将事件添加到 db.我确实导入了 {Events},实际上表单在我进行一些更改之前就可以使用。当我运行它时,我收到一条错误消息:Uncaught TypeError: event.target[matches] is not a function。不幸的是,引发错误的文件对我来说是胡言乱语。

这是我的代码:

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>

很遗憾,在解决此错误之前我无法继续该项目,所以如果有人帮助我,我会非常高兴!

最好的,

【问题讨论】:

  • 嗨,汤姆,感谢您抽出宝贵时间。它是重复的。另一个没有回答......我等了 30 分钟,没有一个新的观点,所以我想它已经死了,这个问题仍然是相关的。您能否取消您的反对票,因为它没有帮助。最好的,

标签: javascript forms reactjs meteor


【解决方案1】:

您的目标元素似乎不支持 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

我希望这能解决您的问题。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 2021-08-29
相关资源
最近更新 更多