我在我的一个应用程序中使用了react引导-类型提前模块。这件事很好,只有一种情况除外。
如果没有结果,我无法按ENTER键提交表单。
如果有建议,我可以选择其中一个选项并提交表单。在这种情况下,能够调用回调onSubmit。
如果有,没有建议提供的反应-引导-提前,不能提交的表单。
如果我使用form.submit()方法onKeyDown事件提交表单,则表单将被提交,但是页面将被刷新,而不是调用回调,这将导致完全超出我的控制结果。
期望的结果:我应该能够调用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>
发布于 2019-07-10 12:09:49
如果你注意到我问题中的代码,我会处理多个事件。特别是onChange
和onKeyDown
。
我们需要了解的关于react-bootstrap-typeahead
的几件事是
onChange
,get bootstrap- the进将将选定的对象传递回回调,而onKeyDown
-bootstrap前进将传递事件,从该事件中,我将使用event.target.value
获得值。onChange
之后才会触发onKeyDown
。因此,如果我们想根据选定的对象执行一些操作,并且要在onKeyDown
回调中使用的值将无法工作。为了克服这种情况,我使用了setTimeout
还删除了form元素。所以我的解决方案
<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) {
if (this.timerid) {
clearTimeout(this.timerid);
}
this.timerid = setTimeout(
() => {
this.sendMessage();
},
300
);
}
}}
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 onClick={() => this.sendMessage() }>Send</button>
这样,我将调用sendMessage
方法onKeyDown
并单击按钮。我还可以使用所选的选项对象。
发布于 2019-07-07 15:33:13
问题很可能是调用this.form.submit()
,它处理DOM中的表单提交(而不是React),正如您所说的,它超出了您的控制范围。它刷新页面,因为您无法控制调用event.preventDefault()
的事件。
当用户按enter键时,您应该调用this.form.submit
而不是this.sendMessage
。您可能是在sendMessage
中调用sendMessage
,因此您应该从onKeyDown
传递该事件
onKeyDown={e => {
if (e.keyCode === 13) {
this.sendMessage(e);
}
}}
这样,无论用户按下submit按钮还是输入,您都将处理相同的表单提交。
https://stackoverflow.com/questions/56922191
复制相似问题