아무거나 붙여넣기
공유하기
간단 요약
- 기사는 React와 스타일링을 결합하여 특정 위치에 텍스트를 입력하는 방법을 소개했다.
- useRef를 활용해 입력 필드를 조작하고, 붙여넣기 기능을 구현하는 사례를 전했다.
- 코드 내 복사된 텍스트가 숫자인지 확인해 코드 배열을 업데이트하는 과정을 밝혔다.
import { useRef } from 'react';
import styled from '@emotion/styled';
import COLOR from '@/constants/COLOR';
//props
interface IInputBlock {
className?: string;
item: string;
index: number; // 인풋창 위치 확인용
codeArr: string[]; // 전체 입력코드확인
disabled?: boolean;
onChange: (code: string[]) => void; //coderArr 수정용
}
const InputBlock = (props: IInputBlock) => {
const { className, item, index, codeArr, onChange, disabled } = props;
const inputRef = useRef<HTMLInputElement>(null);
const value = codeArr[index];
const setValue = (value: string, position: number = 0) => {
const nextCodeArr = [...codeArr];
nextCodeArr[index + position] = value;
onChange(nextCodeArr);
};
// 포커스된 인풋 전 인풋 ref
const nextInput = inputRef.current?.nextElementSibling as HTMLInputElement;
// 포커스된 인풋 다음 인풋 ref
const previousInput = inputRef.current
?.previousElementSibling as HTMLInputElement;
// 붙여넣기
const _onPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
//1. 클립보드에 있는 복사된 텍스트를 가져온다.
//2. 텍스트가 number가 아니면 함수를 종료한다.
//3. 커서위치와, 인풋 인덱스를 확인하여 code array 값을 변경한다.
const clipboardData = e.clipboardData;
const text = clipboardData.getData('text/plain');
if (isNaN(Number(text))) return;
const valueArr = text.split('');
const nextCodeArr = [...codeArr];
valueArr.map((e, i) => {
const plusIndex = inputRef.current?.selectionStart === 0 ? 0 : 1;
nextCodeArr.splice(index + i + plusIndex, 1, e);
});
onChange(nextCodeArr);
};

