简体   繁体   English

使用react和e.preventDefault()阻止表单提交;

[英]Prevent form submission using react and e.preventDefault();

I can't seem to figure this out.... Which event makes sense to bind a function call on to action e.preventDefault(); 我似乎无法弄清楚...。哪个事件将将函数调用绑定到动作e.preventDefault();是有意义的。 in the event that someone clicks enter when they fill in the input tag? 如果有人在填写输入标签时单击回车?

At the moment i get an unwanted refresh happening. 此刻我得到了不必要的刷新。 When i just want to trigger another function when the enter key is hit. 当我只想按下回车键时触发另一个功能。

What should i do? 我该怎么办?

<form onSubmit={this.stopSubmit}>
                        <FormGroup
                            controlId="formBasicText"
                            validationState={getValidationState()}
                        >
                            <ControlLabel>Stuff</ControlLabel>
                            <FormControl
                                type="text"
                                value={this.state.value}
                                placeholder="Enter text"
                                onChange={handleChange}
                                onKeyUp={handleSubmit.bind(this, "test")}

                            />
                            <FormControl.Feedback/>
                            <HelpBlock>Validation is based on string length.</HelpBlock>
                        </FormGroup>
                    </form>

this.stopSubmit应该返回false以防止表单提交

将此添加到表单标签:

<form onSubmit={e => { e.preventDefault(); }}>

The event is the form submission. 该事件是表单提交。 You can read up on it at Mozilla . 您可以在Mozilla上阅读它。

Really it depends on what your form is doing. 确实,这取决于您的表格在做什么。 Usually you will put your event.preventDefault() function call in whatever you're submitting your form to.(ie: what the value of the action parameter is) If its an AJAX call, for instance, you'll want to put that at the beginning of the function. 通常,您会将event.preventDefault()函数调用放在要提交表单的位置。(例如, action参数的值是什么)例如,如果它是AJAX调用,则需要在函数的开头。

At least, thats what I do. 至少,那就是我要做的。 Here is an example of a recent function I used for a form submission that utilizes it. 这是我用于利用表单提交表单的最新功能的示例。

handleFormSubmit = event => {
  event.preventDefault();
  this.searchMovies(this.state.search);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM