Javascript 当在输入中按下 Enter 时,React 会阻止表单提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43750335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:08:49  来源:igfitidea点击:

React prevent form submission when enter is pressed inside input

javascriptreactjs

提问by ErnieKev

React prevent form submission when enter is pressed

按下回车键时,React 会阻止表单提交

I have the following React Search Bar component where the parent container can call using

我有以下 React Search Bar 组件,父容器可以在其中调用使用

<SearchBar onInputChange={this.handleInputChange} />

Everytime the user changes the input, the parent container will be notified. This is why my search bar does not need any submit button.

每次用户更改输入时,都会通知父容器。这就是为什么我的搜索栏不需要任何提交按钮的原因。

However, I am finding that if I press enter inside my search bar, the whole page refreshes. And I dont want that.

但是,我发现如果我在搜索栏中按 Enter,整个页面都会刷新。我不想要那个。

I know if I have a button in the form, I could call event.preventDefault(). But in this case I have no button so I dont know what to do here

我知道如果表单中有一个按钮,我可以调用 event.preventDefault()。但在这种情况下我没有按钮所以我不知道在这里做什么

class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = { value: '' };
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e) {
        this.setState({ value: e.target.value });
        this.props.onInputChange(e.target.value);
    }

    render() {
        return (
        <div id="search-bar">
            <form>
            <FormGroup controlId="formBasicText">
                <FormControl
                type="text"
                onChange={this.handleChange}
                value={this.state.value}
                placeholder="Enter Character Name"
                />          
            </FormGroup>
            </form>
        </div>
        );
    }
}

export default SearchBar

回答by zerkms

You need to create a form handler that would prevent the default form action.

您需要创建一个表单处理程序来阻止默认表单操作。

The simplest implementation would be:

最简单的实现是:

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

But ideally you create a dedicated handler for that:

但理想情况下,您为此创建了一个专用处理程序:

<form onSubmit={this.submitHandler}>

with the following implementation

具有以下实现

submitHandler(e) {
    e.preventDefault();
}

回答by eon

In a React component with a Search input field, nested in a larger (non-React OR React) form, this worked best for me across browsers:

在一个带有搜索输入字段的 React 组件中,嵌套在一个更大的(非 React OR React)表单中,这对我来说最适合跨浏览器:

<MyInputWidget
  label="Find"
  placeholder="Search..."
  onChange={this.search}
  onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}
  value={this.state.searchText} />

(e)=>{e.target.keyCode === 13}(@DavidKamer's answer) is incorrect: You don't want the event.target.That's the input field. You want the event itself. And in React (specifically 16.8, at the moment), you want event.key(e.key, whatever you want to call it).

(e)=>{e.target.keyCode === 13}(@DavidKamer 的回答)不正确:您不想要event.target.That's the input field。你想要事件本身。在 React(目前特别是 16.8)中,你想要event.key(e.key,无论你想怎么称呼它)。

回答by David Kamer

I'm not sure if this works for every situation, as when you press enter in a form's input field you will still trigger the onSubmit method, although the default submit won't occur. This means that you will still trigger your pseudo submit action that you've designed for your form. A one liner with ES6 that solves the problem specifically and entirely:

我不确定这是否适用于每种情况,因为当您在表单的输入字段中按 Enter 键时,您仍然会触发 onSubmit 方法,尽管默认提交不会发生。这意味着您仍然会触发您为表单设计的伪提交操作。带有 ES6 的 one liner 可以专门且完全地解决该问题:

<input onKeyPress={(e)=>{e.target.keyCode === 13 && e.preventDefault();}} />

This solution should have 0 side effects and solves the problem directly.

这个方案应该是0副作用,直接解决问题。

回答by Matteo Galli

The best way to prevent the ENTER, as suggested also by Eon is to add the following to your input element:

正如 Eon 所建议的,防止 ENTER 的最佳方法是将以下内容添加到您的输入元素中

onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }}