每当我在输入文本框上按 Enter 键时,来自 Input 元素的隐式提交会触发提交并重新加载页面:
import React, { Component } from "react";
import { Col, Button, Form, FormGroup, Label, Input } from "reactstrap";
import "./SearchBar.css";
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
term: ""
};
this.handleTermChange = this.handleTermChange.bind(this);
this.handleSearch = this.handleSearch.bind(this);
this.handleEnter = this.handleEnter.bind(this);
}
handleTermChange(e) {
this.setState({ term: e.target.value });
}
handleSearch() {
this.props.searchEngine(this.state.term);
}
handleEnter(e) {
if (e.key === 13) {
this.handleSearch();
}
}
render() {
return (
<Form className="searchbox">
<FormGroup row>
<Label for="searchId" sm={2}>
Search Engine
</Label>
<Col sm={10}>
<Input
type="text"
placeholder="Enter Sth"
onChange={this.handleTermChange}
onKeyDown={this.handleEnter}
/>
</Col>
</FormGroup>
<FormGroup>
<Col sm="2">
<div className="">
<Button
onClick={this.handleSearch}
className="btn"
>
Submit
</Button>
</div>
</Col>
</FormGroup>
</Form>
);
}
}
export default SearchBar;
我只想用上面的处理程序触发搜索功能,但避免隐式提交,即单击
Submit
按钮时的相同功能。否则它只是重新加载页面并清除返回的结果。我做错了什么?我之前没有遇到过基本相同模式的问题。
依赖项:
最佳答案
我发现是 <Form>
元素触发了隐式提交。我将其更改为 <Form className="searchbox" onSubmit={this.handleSubmit}>
并添加一个新函数:
handleSubmit(e) {
e.preventDefault();
this.handleSearch();
}
从问题修改的完整工作代码:
import React, { Component } from "react";
import { Col, Button, Form, FormGroup, Label, Input } from "reactstrap";
import "./SearchBar.css";
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
term: ""
};
this.handleTermChange = this.handleTermChange.bind(this);
this.handleSearch = this.handleSearch.bind(this);
this.handleEnter = this.handleEnter.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleTermChange(e) {
this.setState({ term: e.target.value });
}
handleSearch() {
this.props.searchEngine(this.state.term);
}
handleEnter(e) {
if (e.key === 13) {
this.handleSearch();
}
}
handleSubmit(e) {
e.preventDefault();
this.handleSearch();
}
render() {
return (
<Form className="searchbox" onSubmit={this.handleSubmit}>
<FormGroup row>
<Label for="searchId" sm={2}>
Search Engine
</Label>
<Col sm={10}>
<Input
type="text"
placeholder="Enter Sth"
onChange={this.handleTermChange}
onKeyDown={this.handleEnter}
/>
</Col>
</FormGroup>
<FormGroup>
<Col sm="2">
<div className="">
<Button
onClick={this.handleSearch}
className="btn"
>
Submit
</Button>
</div>
</Col>
</FormGroup>
</Form>
);
}
}
export default SearchBar;
关于javascript - ReactStrap 处理输入隐式提交,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53746769/