ReactJS:如何从另一个事件触发表单提交事件 [英] ReactJS: how to trigger form submit event from another event

查看:364
本文介绍了ReactJS:如何从另一个事件触发表单提交事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个反应事件:

  1. 表单提交事件

  1. Form submit event

sendMessage: function(event){
    console.log(event);
    event.preventDefault();
},

  • keyPress事件

  • keyPress Event

    textareaKeypress: function(event){
        if (event.which == 13 && !event.shiftKey){
            document.getElementById('messagebox').submit();
        }
    },
    

  • ,但是reactJS无法捕获textareaKeypress触发的表单提交.如何通过适当的事件从textareaKeypress调用sendMessage?

    but the reactJS is not capturing the form submit triggered by textareaKeypress. How can I call the sendMessage from textareaKeypress with proper event?

    推荐答案

    我今天学到了一些新东西:这就是DOM的工作原理.

    I learned something new today: this is just how the DOM works.

    MDN网站:

    从基于Gecko的应用程序中调用此方法时,将不会触发表单的onsubmit事件处理程序(例如,onsubmit="return false;").通常,不能保证HTML用户代理会调用它.

    The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.

    根据 HTML规范:

    调用submit()方法时,必须从form元素本身提交form元素,并设置submit()方法标记为.

    The submit() method, when invoked, must submit the form element from the form element itself, with the submitted from submit() method flag set.

    后跟(第4.10.22.3节)

    followed by (section 4.10.22.3)

    如果未设置从submit()方法提交的标志,则在 form 处触发一个简单的事件,该事件起泡并且可以取消,名为submit.

    If the submitted from submit() method flag is not set, then fire a simple event that bubbles and is cancelable named submit, at form.

    因此,如果设置了submit()方法标志,则不会触发该事件.

    So, the event is not fired if the submit() method flag is set.

    我可以通过以下代码获得您(和我)期望的行为( JSFiddle示例):

    I was able to get the behavior you (and I) were expecting via the following code (JSFiddle example):

    <form onSubmit={this.handleSubmit} ref="form">
      <textarea onKeyPress={this.handleKeyPress} />
    </form>
    
    // ...
    
    this.refs.form.getDOMNode().dispatchEvent(new Event("submit"));
    

    (您需要更多详细代码在IE中.)

    jQuery的$(form).submit() 委托 $(form).trigger("submit"),所以我希望这是一个类似的解决方法.

    jQuery's $(form).submit() delegates to $(form).trigger("submit"), so I expect it's a similar workaround.

    这篇关于ReactJS:如何从另一个事件触发表单提交事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆