react 用上下方向键使得input聚焦

import React, { Component } from 'react'

export class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      inputIndex:1
    }
  }
  componentDidMount(){
    let inputGroup = document.getElementsByClassName('input-group');
    //找到所有的input
    console.log(inputGroup);
    document.addEventListener('keydown',(e)=>{
    //监听事件
      if(e.code === 'ArrowDown'){
        console.log('dowm')
        let tempIndex = this.state.inputIndex + 1;
        if(tempIndex > inputGroup.length ){
          tempIndex = 1
        }
        this.setState({
          inputIndex:tempIndex
        })
      }
      if(e.code === 'ArrowUp'){
        console.log('up')
        let tempIndex = this.state.inputIndex - 1;
        if(tempIndex < 1){
          tempIndex = inputGroup.length
        }
        this.setState({
          inputIndex:tempIndex
        })
      }
      // inputGroup.forEach(ele=>{
      //   ele.autofocus = false;
      // })
      // let i = inputGroup.length
      // while(i--){
      //   inputGroup[i].children[0].autofoucs = false;
      // }
      //让input聚焦
      inputGroup[this.state.inputIndex-1].children[0].focus();
    })
  }



  render() {
    return (
      <div className="App">
      <div className='input-group'>
        <input placeholder='请输入'></input>
      </div>
      <div className='input-group'>
      <input placeholder='请输入'></input>
      </div>
      <div className='input-group'>
      <input  placeholder='请输入'></input>
      </div>
    </div>
    );
  }
}

export default App

你可能感兴趣的:(工作笔记)