React 17과 TypeScript 환경에서 클래스 컴포넌트를 사용하고, 입력 필드가 3개일 때:
1번 입력에서 Enter → 2번으로 포커스 이동
2번 입력에서 Enter → 3번으로 포커스 이동
3번 입력에서 Enter → 조회 함수 호출
하는 예제

import React, { Component, createRef } from 'react';

interface State {
condition1: string;
condition2: string;
condition3: string;
}

class SearchForm extends Component<{}, State> {
input1Ref = createRef();
input2Ref = createRef();
input3Ref = createRef();

state: State = {

condition1: '',
condition2: '',
condition3: '',

};

handleKeyDown = (e: React.KeyboardEvent, fieldIndex: number) => {

if (e.key === 'Enter') {
  e.preventDefault();

  switch (fieldIndex) {
    case 1:
      this.input2Ref.current?.focus();
      break;
    case 2:
      this.input3Ref.current?.focus();
      break;
    case 3:
      this.handleSearch();
      break;
    default:
      break;
  }
}

};

handleChange = (e: React.ChangeEvent) => {

const { name, value } = e.target;
this.setState({ [name]: value } as Pick<State, keyof State>);

};

handleSearch = () => {

const { condition1, condition2, condition3 } = this.state;
console.log('검색 조건:', condition1, condition2, condition3);
// 실제 검색 함수 로직 여기에 작성
alert(`조회 호출: ${condition1}, ${condition2}, ${condition3}`);

};

render() {

const { condition1, condition2, condition3 } = this.state;

return (
  <form>
    <input
      type="text"
      name="condition1"
      value={condition1}
      onChange={this.handleChange}
      onKeyDown={(e) => this.handleKeyDown(e, 1)}
      ref={this.input1Ref}
      placeholder="조건 1"
    />
    <br />
    <input
      type="text"
      name="condition2"
      value={condition2}
      onChange={this.handleChange}
      onKeyDown={(e) => this.handleKeyDown(e, 2)}
      ref={this.input2Ref}
      placeholder="조건 2"
    />
    <br />
    <input
      type="text"
      name="condition3"
      value={condition3}
      onChange={this.handleChange}
      onKeyDown={(e) => this.handleKeyDown(e, 3)}
      ref={this.input3Ref}
      placeholder="조건 3"
    />
    <br />
    <button type="button" onClick={this.handleSearch}>
      조회
    </button>
  </form>
);

}
}

export default SearchForm;

onKeyDown={(e) => handleKeyDown(e, 1)} 에서 오류가 발생하는 이유는 TypeScript가 e의 타입을 명확히 추론하지 못해 발생하는 타입 불일치입니다.

onKeyDown={(e: React.KeyboardEvent) => handleKeyDown(e, 1)}

tag: none

댓글추가