如何以正确的方式触发表单提交?

时间:2015-02-24 20:23:40

标签: javascript jquery reactjs react-jsx

我需要在表单上触发提交,然后使用javascript处理它。这就是组件的样子

var CommentForm = React.createClass({
  handleSubmit: function(e) {
    alert("YES again");
    return;
  },
  render: function() {
    return (
        <div className="postCon">
          <form className="commentForm" onSubmit={this.handleSubmit}>
            <textarea className="textA input" placeholder="Your comment" ref="author" />
          </form>
        </div>
    );
  }
})

这是用来触发提交到正确的反应方法的jquery

<script>
        $(function(){
            $('.textA').autosize();
        });
        $('.textA').keypress(function (e) {
            if (e.which == 13 && !event.shiftKey) {
                e.preventDefault();
                $(this).closest("form").submit();
                return false; //prevent duplicate submission
            }
        });
    </script>

问题是表单将被发送并且handleSubmit永远不会被触发?这是正确的做法,还是我过于复杂的事情?

1 个答案:

答案 0 :(得分:0)

使用来自React的键盘事件 - http://facebook.github.io/react/docs/events.html 例如:

var CommentForm = React.createClass({
  handleSubmit: function(e) {
    alert("YES again");
    return;
  },
  handleKeyPress: function(e){console.log(e.which);if(e.which == 13){this.handleSubmit();}},
  render: function() {
    return (
        <div className="postCon">
          <form className="commentForm" onSubmit={this.handleSubmit}>
            <textarea onKeyPress={this.handleKeyPress} className="textA input" placeholder="Your comment" ref="author" />
          </form>
        </div>
    );
  }
})