gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:43:34 24 4
gpt4 key购买 nike

我正在 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 的内置生命周期方法。首先,为您想要获得焦点的元素创建一个 ref(在本例中,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>);
}
}

关于reactjs - 专注于 div 而不在 React 中单击以启用模块上的键盘导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53287098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com