每当我将重点放在“输入”文本框上时按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
按钮时使用相同的功能。否则,它只是重新加载页面并清除返回的结果。
我做错了什么?我以前从未遇到过使用相同模式的问题。
依赖项:
答案 0 :(得分:2)
我发现是<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;
答案 1 :(得分:1)
您需要防止在按下Enter
键时发生默认事件。
handleEnter(e) {
if (e.key === 13) {
e.preventDefault();
this.handleSearch();
}
}
e.preventDefault()
告诉用户代理,如果未明确处理事件,则不应像通常那样采取其默认操作。