-
Notifications
You must be signed in to change notification settings - Fork 13
Open
Labels
Description
在搜索功能开发的时候,有时会碰到这种需求:点击输入法上的搜索按钮进行关键词搜索。这个需求可以拆分成两个需求:
-
输入法有“搜索”按钮;
-
点击“搜索”按钮执行搜索事件。
第一个需求很简单,设置input的type="search"就可以。
<input type="search" placeholder="搜索关键词" />第二个需求,可能很少接触,这个时候就需要借用form表单的submit提交。
<form onsubmit="handleSubmit()">
<input type="search" placeholder="搜索关键词" />
</form>重点来了
如果不加处理,就会触发form表单submit默认的页面刷新事件。我们必须手动消除form表单submit事件的页面默认刷新行为。下面推荐三种写法:
- 外部
return false
<form onsubmit="handleSubmit();return false">
<input type="search">
</form>function handleSubmit() {
...
}- 内部
return false
<form onsubmit="handleSubmit()">
<input type="search">
</form>function handleSubmit() {
...
return false
}- 阻止默认行为
preventDefault
<form onsubmit="handleSubmit(event)">
<input type="search">
</form>function handleSubmit(event) {
e.preventDefault(event);
...
}But
1、2两种写法在React均不支持,只能采用preventDefault了,写法如下:
handleSubmit(event){
event.preventDefault();
...
}
render(){
return (
<form onSubmit={this.handleSubmit}>
<input type="search" placeholder="搜索关键词" />
</form>
)
}不过,有个细节不知道大家注意到没,上面第三种写法的handleSubmit在onsubmit里显示的传递了event,而这里并没有。是我多此一举还是有所考虑?大家思考下,我下次再说。
Reactions are currently unavailable