使用点击或者按下Escape键来调用setState。

4

我有一个React模态框,通过处理函数来打开和关闭。

我希望可以通过点击事件或使用esc键来调用该函数,以提高可访问性。

如何同时跟踪两个事件?

目前,我已经实现了esc事件:

 handleCloseModal = event => {
    if (event.keyCode === 27) {
      this.setState({ modal: false })
    }
  }

但这样我就失去了对

点击功能的支持。
<Modal 
  onClick={handleCloseModal} 
  role="button" tabIndex={0} 
  onKeyDown={handleCloseModal}
 />

我该如何处理这个问题?

2个回答

3
可能的解决方案可以是:创建一个单独的函数来关闭 Modal。使用该函数作为 onClick 的处理函数,并在按下 esc 键时调用它。
像这样:
<Modal 
  onClick={handleCloseModal} 
  role="button" tabIndex={0} 
  onKeyDown={handleKeyDown}
/>

handleKeyDown = event => {
  if (event.keyCode === 27) {
    handleCloseModal()
  }
}

handleCloseModal = () => this.setState({ modal: false })

非常好。非常感谢!如果您认为有比这种方法更优的方法,请告诉我。 - Null isTrue

1
如果我理解正确,您想要重用相同的关闭事件处理程序来处理单击和按键事件。区分这两种事件类型的一种方法是通过instanceof检测event对象的类型,如下所示:
handleCloseModal = event => {

    // if event is mouse event, handle it accordingly
    if(event instanceof MouseEvent) {

       // if mouse click detected hide the modal
       this.setState({ modal: false })
    }
    // if event is keyboard event, handle it accordingly
    else if(event instanceof KeyboardEvent) {

        // if escape key pressed for keyboard event then hide the modal
        if (event.keyCode === 27) {
          this.setState({ modal: false })
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接