每当我在输入文本框上按Enter键时,输入元素中的隐式提交就会触发提交并重新加载页面:
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按钮时使用相同的函数。否则,它只是重新加载页面并清除返回的结果。
我做错什么了?我以前没有经历过类似的问题。
依赖关系:
发布于 2018-12-13 02:57:56
我发现触发隐式提交的是<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;发布于 2018-12-12 16:31:39
当Enter键按下时,您需要防止默认事件。
handleEnter(e) {
if (e.key === 13) {
e.preventDefault();
this.handleSearch();
}
}e.preventDefault()告诉用户代理,如果事件没有被显式处理,那么它的默认操作就不应该像通常那样进行。
https://stackoverflow.com/questions/53746769
复制相似问题