Reactjs 使用onKeyDown聚焦下一个元素
我在React中循环浏览元素列表,并在网格中显示它们。我希望能够使用键盘在网格中导航 此函数用于渲染网格:Reactjs 使用onKeyDown聚焦下一个元素,reactjs,tabindex,Reactjs,Tabindex,我在React中循环浏览元素列表,并在网格中显示它们。我希望能够使用键盘在网格中导航 此函数用于渲染网格: listOfEmployees() { const results = []; while (this.state.filteredView.length) { results.push(this.state.filteredView.splice(0, 3)) } return results.map(result => &l
listOfEmployees() {
const results = [];
while (this.state.filteredView.length) {
results.push(this.state.filteredView.splice(0, 3))
}
return results.map(result =>
<Row
style={{display: 'contents'}}
onKeyDown={this.handleKeyPress}
tabIndex="0"
>
{result.map(e =>
<Col sm={4}>
<Link
to={`/employee/${e.id}`}
style={{textDecoration: 'none', color: 'black'}}
className="Link"
>
<Wrapper>
<Name>
{e.name}
</Name>
<JobTitle>
{e.job_titles}
</JobTitle>
</Wrapper>
</Link>
</Col>
)}
</Row>
)
}
这是可行的,但它是硬编码的,所以我只关注第二个div(
links[1]
)。如何使其动态化,以便每次按右箭头键都能将焦点移到一个div上?解决了这个问题。我在
中添加了一个id,然后使用该值获取下一个元素
<Link
to={`/employee/${e.id}`}
style={{textDecoration: 'none', color: 'black'}}
className="Link"
id={e.id}
>
希望这也能帮助其他人
<Link
to={`/employee/${e.id}`}
style={{textDecoration: 'none', color: 'black'}}
className="Link"
id={e.id}
>
handleKeyPress = (e) => {
const link = document.getElementsByClassName('Link')
if (e.keyCode === 39) {
const targetId = parseInt(e.target.id) - 1
link[targetId + 1].focus()
} else if (e.keyCode === 37) {
const targetId = parseInt(e.target.id) - 1
link[targetId - 1].focus()
}
}