专注于div而无需在React中单击以启用模块上的键盘导航

时间:2018-11-13 18:09:32

标签: reactjs focus

我正在React中从头开始编写图片库,单击图片时会弹出一个模态(与我的图片库组件分开的组件)。我想用左右箭头在图片之间导航,不仅要在屏幕上添加箭头(onclick),而且目前仅在单击模式时才关注模式,然后我也可以使用键盘导航(onKeyDown)。

我已经在div中添加了tabIndex =“ 0”,但是我仍然需要单击div一次来关注它。

<div tabIndex="0" onKeyDown={(event) => this.onKeyNavigation(event, ImageUrl, currentIndex, ImageUrls)}>

onKeyNavigation = (event, ImageUrl, currentIndex, ImageUrls) => {

if ((event.keyCode) === 39) {
    this.props.loadNext(ImageUrl, currentIndex, ImageUrls)
  }
  else if ((event.keyCode) === 37) {
    this.props.loadPrevious(ImageUrl, currentIndex, ImageUrls)
  }
  else if ((event.keyCode) === 27) {
    this.props.onClose()
  }
 }

3 个答案:

答案 0 :(得分:0)

渲染后,您需要在要聚焦的focus()上触发一个<div>事件。

最简单的方法是使用React的内置生命周期方法。首先,为要关注的元素创建一个引用(在这种情况下,div监听keyDown事件)。然后,您可以使用组件的focus()方法在该节点上调用componentDidMount()

class ImageGallery extends React.Component {
    construtor(){
        super();

        // Create the ref in the constructor
        this.focusRef = React.createRef();
    }

    /* your other methods here */

    componentDidMount(){
        // Focus on the rendered div using the DOM focus() method
        this.focusRef.focus();
    }

    render(){
        // Set the ref in your render() method
        return(<div ref={this.focusRef} onKeyDown={this.handle}></div>);
    }
}

答案 1 :(得分:0)

因此解决方案是:

componentDidUpdate(){ this.focusRef.current.focus(); }

答案 2 :(得分:0)

dcastrodale,您的回答对我很有帮助,但是由于某种原因,这直到我将引用放置在setTimeout()内的componentDidMount()中才起作用。这是我在页面加载时专注于特定div的工作。

---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/owlready2/namespace.py in load(self, only_local, fileobj, reload, reload_if_newer, **args)
    769         if _LOG_LEVEL: print("* Owlready2 *     ...loading ontology %s from %s..." % (self.name, f), file = sys.stderr)
--> 770         try:     fileobj = urllib.request.urlopen(f)
    771         except:  raise OwlReadyOntologyParsingError("Cannot download '%s'!" % f)

HTTPError: HTTP Error 308: Permanent Redirect

During handling of the above exception, another exception occurred:

OwlReadyOntologyParsingError              Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/owlready2/namespace.py in load(self, only_local, fileobj, reload, reload_if_newer, **args)
    769         if _LOG_LEVEL: print("* Owlready2 *     ...loading ontology %s from %s..." % (self.name, f), file = sys.stderr)
    770         try:     fileobj = urllib.request.urlopen(f)
--> 771         except:  raise OwlReadyOntologyParsingError("Cannot download '%s'!" % f)
    772         try:     new_base_iri = self.graph.parse(fileobj, default_base = self.base_iri, **args)
    773         finally: fileobj.close()

OwlReadyOntologyParsingError: Cannot download 'http://purl.org/dc/elements/1.1'!

这对我非常有用,我什至可以用键盘按下按钮元素,而鼠标指针永远不会进入浏览器窗口。

再次感谢dcastrodale!您的回答引导了我正确的方向。