javascript - form.submit 回调没有被调用
问题描述
我在我的一个应用程序中使用 react-bootstrap-typeahead 模块。这工作正常,除了一种情况。
如果没有结果,我无法通过按 ENTER 键提交表单。
IE; 如果react-bootstrap-typeahead 提供了建议,我可以选择其中一个选项并提交表单。在这种情况下,能够调用回调 onSubmit。
如果react-bootstrap-typeahead没有提供建议,则无法提交表单。
如果我使用 form.submit() 方法 onKeyDown 事件提交表单,表单将被提交,但是,页面会刷新而不是调用回调,这导致我完全无法控制结果。
期望的结果:如果 react-bootstrap-typeahead 提供了建议,即使没有提供建议,我也应该能够调用 onSubmit 回调。
这是我的代码。
<form ref={(form) => this.form = form} onSubmit={this.sendMessage}>
<Typeahead
id="rbt-example"
dropup={true}
ref={(typeahead) => this.typeahead = typeahead}
onChange={this.valueChanged}
onInputChange={this.updateQuery}
onBlur={(e) => this.updateQuery(e.target.value, e)}
onKeyDown={(e) => {
// Submit the form when the user hits enter.
if (e.keyCode === 13) {
this.form.submit();
}
}}
options={options}
placeholder="Type your queries here..."
renderMenu={(results, menuProps) => {
// Hide the menu when there are no results.
if (!results.length) {
return null;
}
return <TypeaheadMenu {...menuProps} options={results} />;
}}
/>
<button type="submit">Submit</button>
</form>
解决方案
问题可能是调用this.form.submit()
,它处理 DOM 中的表单提交(而不是 React),并且正如您所说,它使您无法控制。它正在刷新页面,因为您无法控制要调用的事件event.preventDefault()
。
而不是this.form.submit
,您应该this.sendMessage
在用户按下回车时调用。大概你正在打电话event.preventDefault
,sendMessage
所以你应该通过 from 传递事件onKeyDown
:
onKeyDown={e => {
if (e.keyCode === 13) {
this.sendMessage(e);
}
}}
这样,无论是响应用户按下提交按钮还是输入,您都将以相同的方式处理表单提交。
推荐阅读
- excel - VBA (Excel) - 在运行时获取活动对象 (ActiveX ComboBox)
- angularjs - $location.path 在重定向到另一个页面时不起作用
- android - 错误:在 null 上调用了 tabLabel
- elasticsearch - 使用自定义分析器时如何查看分析的文本?
- php - 如何在 wordpress 中使用带有联系表 7 的 mailjet
- python - 测试布尔变量
- c++ - 如何在 C++ 中获取自动变量的类型
- python - 使用python抓取html元素的内部标签时出错
- mysql - MySql:按日期计算值的出现次数
- mysql - 从 Spring Boot 获取 MySQL thread_id