본문 바로가기

기타 보관함/개발자정보

React Enter 이벤트 처리 예제(Class Component + TypeScript)

반응형
import React, { Component, createRef } from 'react';

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

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

  state: State = {
    condition1: '',
    condition2: '',
    condition3: '',
  };

  handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, 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<HTMLInputElement>) => {
    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;

 

observer()와 함께 사용하는 함수형 컴포넌트 환경을 사용 중입니다 (아마 MobX와 함께 사용 중이신 것 같습니다).

그래서 코드도 함수형 컴포넌트 스타일로 작성해야 합니다. 아래는 조건 3개를 입력받고, Enter 키 입력 시 원하는 동작을 수행하는 함수형 컴포넌트 + TypeScript + observer() 형태의 예제입니다.

import React, { useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';

export const TestSearch = observer(() => {
  const [condition1, setCondition1] = useState('');
  const [condition2, setCondition2] = useState('');
  const [condition3, setCondition3] = useState('');

  const input1Ref = useRef<HTMLInputElement>(null);
  const input2Ref = useRef<HTMLInputElement>(null);
  const input3Ref = useRef<HTMLInputElement>(null);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, fieldIndex: number) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (fieldIndex === 1) {
        input2Ref.current?.focus();
      } else if (fieldIndex === 2) {
        input3Ref.current?.focus();
      } else if (fieldIndex === 3) {
        handleSearch();
      }
    }
  };

  const handleSearch = () => {
    console.log('검색 조건:', condition1, condition2, condition3);
    alert(`조회 호출: ${condition1}, ${condition2}, ${condition3}`);
  };

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

 

 

오류 발생해서 수정

onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => handleKeyDown(e, 1)}
반응형