我正在 React 中从头开始编写一个图像库,当单击图像时,会弹出一个模式(与我的库组件分开的组件)。我想要使用左右箭头在图片之间导航,不仅仅是屏幕上添加的箭头(onclick),但目前它只关注当我单击一次时的模式,然后我也可以使用键盘导航(onKeyDown)。
我已将 tabIndex="0" 添加到我的 div 中,但我仍然需要单击该 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()
}
}
你需要发射一个focus()
事件于<div>
您希望在渲染后获得焦点。
最简单的方法是使用 React 的内置生命周期方法。首先,为您想要获得焦点的元素创建一个引用(在本例中为监听 keyDown 事件的 div)。然后,您可以致电focus()
在你的组件的那个节点上componentDidMount()
method:
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>);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)