wusb / blog

🖋 Personal blog, Welcome Fork, Watch & Star
http://simbawu.com
MIT License
50 stars 14 forks source link

如何避免form表单onSubmit后页面自动刷新? #7

Open wusb opened 6 years ago

wusb commented 6 years ago

在搜索功能开发的时候,有时会碰到这种需求:点击输入法上的搜索按钮进行关键词搜索。这个需求可以拆分成两个需求:

  1. 输入法有“搜索”按钮;

  2. 点击“搜索”按钮执行搜索事件。

第一个需求很简单,设置inputtype="search"就可以。

<input type="search" placeholder="搜索关键词" />

第二个需求,可能很少接触,这个时候就需要借用form表单的submit提交。

<form onsubmit="handleSubmit()">
   <input type="search" placeholder="搜索关键词" />
</form>

重点来了

如果不加处理,就会触发form表单submit默认的页面刷新事件。我们必须手动消除form表单submit事件的页面默认刷新行为。下面推荐三种写法:

  1. 外部return false
<form onsubmit="handleSubmit();return false">
   <input type="search">
</form>
function handleSubmit() {
   ...
}
  1. 内部return false
<form onsubmit="handleSubmit()">
   <input type="search">
</form>
function handleSubmit() {
   ...
   return false
}
  1. 阻止默认行为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>
    )
}

不过,有个细节不知道大家注意到没,上面第三种写法的handleSubmitonsubmit里显示的传递了event,而这里并没有。是我多此一举还是有所考虑?大家思考下,我下次再说。

llh1187 commented 3 years ago

第一个需求很简单,设置input的type="search"就可以。


刚刚测试了 不行哦

llh1187 commented 3 years ago

第一个需求很简单,设置input的type="search"就可以。

----------------------------------------------------------- 刚刚测试了 不行哦

iphone11和小米都不起作用