首页 > 解决方案 > 如何使用反应在网络聊天中向上/向下键

问题描述

我目前正在使用 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>

标签: javascriptreactjsbotframeworkbots

解决方案


从您的重复问题的答案: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. 您将需要在您的状态中定义一个新属性,以跟踪键盘选择了哪个建议。我保留了highlightedIndexreact-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,
    });
  }
}

推荐阅读