javascript - 如何使用反应在网络聊天中向上/向下键
问题描述
我目前正在使用 react js 做 bot-framework 网络聊天应用程序。我想知道我怎样才能上/下键。因为我想使用箭头键通过建议列表进行选择或突出显示。我用于反应组件的代码附在下面,PFA,
async handleSuggestionClick(val) {
const newValue = val.currentTarget.textContent;
await this.setState({ typingChecking: "false" },
() => { console.log(this.state.typingChecking) });
await this.setState({ suggestions: [] },
() => { console.log(this.state.suggestions) });
this.state.suggestionCallback.dispatch({
type: 'WEB_CHAT/SET_SEND_BOX',
payload: {
text: newValue,
}
});
await this.setState({ typingChecking: "true" },
() => { console.log(this.state.typingChecking) });
}
<div className="react-container webchat" >
<ReactWebChat directLine={this.state.directLine}
webSocket={true}
store={this.state.storeValue}
sendTypingIndicator={true} />
<div className="SuggestionParent" id="Suggestion1">
{this.state.suggestions.map(suggestion => (
<div className="Suggestion"
onClick={this.handleSuggestionClick}
onKeyDown={this.handleKeyDown}>
{suggestion
.toLowerCase()
.startsWith(this.state.suggestionTypedText) ?
(<div>
<b>
{this.state.suggestionTypedText}
</b>
{suggestion
.toLowerCase()
.replace(this.state.suggestionTypedText, "")}
</div>) :
(<div>{suggestion}</div>
)
}
</div>
))
}
</div>
解决方案
从您的重复问题的答案:botframework Webchat React 中的建议列表问题
键盘事件通常在 React 中使用
onKeyDown
属性来处理。我已将其放置在包含 Web Chat 和您的建议父级的元素上:<div className={ROOT_CSS} onKeyDown={this.handleKeyDown.bind(this)}> <div className={WEB_CHAT_CSS + ''}> <ReactWebChat
这将处理所有按键,因此您需要一种方法来路由到正确键的功能。您可以使用
switch
语句,但 [react-autocomplete][3] 的源代码使用查找对象,我认为这很聪明。keyDownHandlers = { ArrowDown(event) { this.moveHighlight(event, 1); }, ArrowUp(event) { this.moveHighlight(event, -1); }, Enter(event) { const {suggestions} = this.state; if (!suggestions.length) { // menu is closed so there is no selection to accept -> do nothing return } event.preventDefault() this.applySuggestion(suggestions[this.state.highlightedIndex]); }, } handleKeyDown(event) { if (this.keyDownHandlers[event.key]) this.keyDownHandlers[event.key].call(this, event) }
我已将向上和向下箭头的功能集中到一个功能中:
moveHighlight
. 您将需要在您的状态中定义一个新属性,以跟踪键盘选择了哪个建议。我保留了highlightedIndex
react-autocomplete 的名称。moveHighlight(event, direction) { event.preventDefault(); const { highlightedIndex, suggestions } = this.state; if (!suggestions.length) return; let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length; if (newIndex !== highlightedIndex) { this.setState({ highlightedIndex: newIndex, }); } }
推荐阅读
- rust - 当参数在 Rust 中作为引用提供时,我们应该在函数体内使用参数引用吗?
- python - 如何忽略此参数的区分大小写?
- flutter - 如何处理单击 sliverlist 项目?
- eclipse - Eclipse Py-dev,深色主题在键入时删除文本突出显示?
- sendgrid - SendGrid 邮件始终处于待处理状态
- php - 如何自动为 Laravel Blade 模板中的所有链接添加一些查询参数?
- python - 如何复制绘图:Python 中的密度条形图
- linux - 如何找到除其中一个之外的 docker 容器 ID 列表?
- upload - Vaadin 14 上传图片,检索 tmp 名称
- json - JSON 将对象映射到 React 中的表