【问题标题】:Reactjs form onSubmit not workingReactjs表单onSubmit不起作用
【发布时间】:2015-08-14 04:20:08
【问题描述】:

我正在尝试构建一个动态 div,其中包含基于状态的不同组件。我有我的自定义组件 Active、Stable 和 Form。

render: function () {
  var components = [];
  if (this.state.isActive) {
     components.push(React.DOM.Active));
  } 
  if (this.state.isStable) {
     components.push(React.DOM.Stable({}));
  }
  if (this.state.visible) {
    components.push(React.DOM.Form({}));
  }
  return React.DOM.div({}, components);
}

Form 组件是一个简单的表单,具有

handleSubmit(e) {
  e.preventDefault();
  console.log('Submitted');
}
render: function() {
  return React.DOM.form({onSubmit: this.handleSubmit}, [React.DOM.button({},'Submit')]);

}

handleSubmit 方法永远不会被调用。但是如果我将代码更改为:

render: function () {
  var components = [];
  components.push(React.DOM.Form({}));
  return React.DOM.div({}, components);
}

有谁知道问题出在哪里?

【问题讨论】:

  • 更改代码时会发生什么?你没有指定。
  • 糟糕!我忘记指定了!它在控制台中写入“已提交”,并阻止事件的默认行为。

标签: forms button submit reactjs


【解决方案1】:

handleSubmit 方法编写不正确。应该是

handleSubmit: function(e) {
  e.preventDefault();
  console.log('Submitted');
},
//(dont forget the comma to separate methods  :)

【讨论】:

    【解决方案2】:

    您需要在React.DOM.form 呼叫中使用{onSubmit: this.handleSubmit}

    【讨论】:

    • 我已经写好了,但是忘记粘贴了。
    猜你喜欢
    • 2015-11-11
    • 2017-05-03
    • 2018-08-06
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多