在 React 中专注于 div,无需单击即可在模块上启用键盘导航

Gab*_*nus 5 focus reactjs

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

我已将 tabIndex="0" 添加到我的 div 中,但我仍然需要单击该 div 一次才能聚焦于它。

<div tabIndex="0" onKeyDown={(event) => this.onKeyNavigation(event, ImageUrl, currentIndex, ImageUrls)}>
Run Code Online (Sandbox Code Playgroud)
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()
  }
 }
Run Code Online (Sandbox Code Playgroud)

小智 2

在渲染后,您需要在想要获得焦点的focus()对象上触发一个事件。<div>

最简单的方法是使用 React 的内置生命周期方法。首先,为您想要获得焦点的元素创建一个引用(在本例中为监听 keyDown 事件的 div)。然后,您可以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>);
    }
}
Run Code Online (Sandbox Code Playgroud)