Open wusb opened 6 years ago
在搜索功能开发的时候,有时会碰到这种需求:点击输入法上的搜索按钮进行关键词搜索。这个需求可以拆分成两个需求:
输入法有“搜索”按钮;
点击“搜索”按钮执行搜索事件。
第一个需求很简单,设置input的type="search"就可以。
input
type="search"
<input type="search" placeholder="搜索关键词" />
第二个需求,可能很少接触,这个时候就需要借用form表单的submit提交。
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() { ... }
<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); ... }
1、2两种写法在React均不支持,只能采用preventDefault了,写法如下:
handleSubmit(event){ event.preventDefault(); ... } render(){ return ( <form onSubmit={this.handleSubmit}> <input type="search" placeholder="搜索关键词" /> </form> ) }
不过,有个细节不知道大家注意到没,上面第三种写法的handleSubmit在onsubmit里显示的传递了event,而这里并没有。是我多此一举还是有所考虑?大家思考下,我下次再说。
handleSubmit
onsubmit
event
刚刚测试了 不行哦
第一个需求很简单,设置input的type="search"就可以。 ----------------------------------------------------------- 刚刚测试了 不行哦
----------------------------------------------------------- 刚刚测试了 不行哦
iphone11和小米都不起作用
在搜索功能开发的时候,有时会碰到这种需求:点击输入法上的搜索按钮进行关键词搜索。这个需求可以拆分成两个需求:
输入法有“搜索”按钮;
点击“搜索”按钮执行搜索事件。
第一个需求很简单,设置
input
的type="search"
就可以。第二个需求,可能很少接触,这个时候就需要借用
form
表单的submit
提交。重点来了
如果不加处理,就会触发
form
表单submit
默认的页面刷新事件。我们必须手动消除form
表单submit
事件的页面默认刷新行为。下面推荐三种写法:return false
return false
preventDefault
But
1、2两种写法在React均不支持,只能采用
preventDefault
了,写法如下:不过,有个细节不知道大家注意到没,上面第三种写法的
handleSubmit
在onsubmit
里显示的传递了event
,而这里并没有。是我多此一举还是有所考虑?大家思考下,我下次再说。