Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wusb opened this issue Mar 20, 2018 · 2 comments
Open

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

wusb opened this issue Mar 20, 2018 · 2 comments

Comments

@wusb
Copy link
Owner

wusb commented Mar 20, 2018

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

  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
Copy link

llh1187 commented Dec 29, 2020

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

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

@llh1187
Copy link

llh1187 commented Dec 29, 2020

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

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

iphone11和小米都不起作用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants