Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

javascript - React prevent form submission when enter is pressed inside input

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
question from:https://stackoverflow.com/questions/43750335/react-prevent-form-submission-when-enter-is-pressed-inside-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...