如何防止在输入字段中按Enter键时发生重定向?

问题描述:

我有一个带有输入电子邮件的表格.

I have a form with an input for email.

<form action="." method="post">
    <div id="email-wrapper">
        <input type="text" placeholder="Your email" name="email" ref="email" onChange={this.handleChange}/>
    </div>
    <span class="signup-error">Please provide a valid email.</span>
</form>
....
....
<button id="next-btn" onClick={this.saveAndContinue}>Next</button>

按下按钮时,我使用简单的正则表达式进行验证,以确认其为电子邮件地址,并且此方法工作正常.但是,如果按Enter键( key = 13 ),它会定向到其他页面,这是我看到的错误:

When the button is pressed I validate with simple regex to confirm that its an email address, and this is working fine. However, if I press enter (key=13), it directs to someother page and this is the error I see:

无法发布/

我以为该脚本可以解决问题,但事实并非如此:

I thought this script would handle the problem, but it didn't:

handleChange = (event) => {
    event.preventDefault();
    var keyCode = event.keyCode || event.which;
    if (keyCode == '13'){
        console.log('enter pressed');
    }
}

这是怎么回事?如何防止在输入字段中按Enter键时发生的重定向?请你帮助我好吗.谢谢.

What's going on? How can I prevent redirection that occurs when I press enter key in an input field? Could you please help me. Thank you.

尝试处理 onKeyPress 事件.在 handleChange 函数中按下Enter键后,您需要返回false .您需要在事件联结中的 handleChange 函数中返回返回值;像

Try handling the onKeyPress event. You'll need to return false when the Enter key is pressed in your handleChange function. You'll need to return the return value in your handleChange function in your event wireup; something like

<input type="text" onKeyPress="return handleChange(event)" />

总而言之,您可以尝试:

In all, you can try:

<form action="." method="post">
    <div id="email-wrapper">
        <input type="text" placeholder="Your email" name="email" ref="email" onKeyPress={return this.handleChange(event)}/>
    </div>
    <span class="signup-error">Please provide a valid email.</span>
</form>
....
....
<button id="next-btn" onClick={this.saveAndContinue}>Next</button>

<script>
    handleChange = (event) => {
        event.preventDefault();
        var keyCode = event.keyCode || event.which;
        if (keyCode == '13'){
            console.log('enter pressed');
            return false;
        }
    }
</script>