本文介绍了当在输入中按下 Enter 时,React 会阻止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

class SearchBar 扩展组件 {构造函数(道具){超级(道具);this.state = { 值:'' };this.handleChange = this.handleChange.bind(this)}句柄变化(e){this.setState({ value: e.target.value });this.props.onInputChange(e.target.value);}使成为() {返回 (<div id="搜索栏"><表格><FormGroup controlId="formBasicText"><表单控件类型=文本"onChange={this.handleChange}值={this.state.value}placeholder="输入角色名称"/></FormGroup></表单>

);}}导出默认搜索栏

解决方案

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

最简单的实现是:

{ e.preventDefault();}}>

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

具有以下实现

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

React prevent form submission when enter is pressed

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

<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.

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

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
解决方案

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();
}

这篇关于当在输入中按下 Enter 时,React 会阻止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:59