Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用onKeyDown聚焦下一个元素_Reactjs_Tabindex - Fatal编程技术网

Reactjs 使用onKeyDown聚焦下一个元素

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

我在React中循环浏览元素列表,并在网格中显示它们。我希望能够使用键盘在网格中导航

此函数用于渲染网格:

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()
    }
  }