문제
input 태그를 사용자가 원하는대로 임의로 생성해서 그 값을 관리하려고 하는데 나중에 reset을 좀 쉽게 하려면 ref를 사용하는게 좋을 것 같았는데
문제는 input이 한개가 아니고, 사용자가 원하는 대로 생성할 수 있어서 그에 맞게 useRef를 하나씩 계속 만드는 건 조금 비효율적이라고 생각
코드
const weightRefs = useRef([]);
const repsRefs = useRef([]);
//Form 컴포넌트에서 각 input의 입력값을 한번에 관리
return (
<>
<Nav></Nav>
<form
onSubmit={(e) => {
e.preventDefault();
setIsSubmit(true);
console.log(weightRefs);
}}>
{inputList.map((number, idx) => {
return (
<div className={style.box} key={idx}>
<span>{number}</span>
<Input inputRef={weightRefs} order={number}></Input>
<Input inputRef={repsRefs} order={number}></Input>
</div>
);
})}
<Button content="등록"></Button>
</form>
</>
);
};
- Form이라는 부모 컴포넌트에서 refs를 생성한 다음, 각 Input 컴포넌트에 props로 전달해줌
import { useRef, useEffect } from "react";
const Input = ({ order, inputRef }) => {
return <input ref={(el) => (inputRef.current[order] = el)}></input>;
};
export default Input;
- Input 컴포넌트에서는 그냥 ref={inputRef}를 하는 것이 아니라, inputRef.current[index]를 통해서 하나의 ref에 여러개의 DOM을 등록
- 이렇게 하면 나중에 value값을 초기화 할 때 refs.current를 반복문 돌리면 됨
'REACT' 카테고리의 다른 글
cloneElement (0) | 2023.07.25 |
---|---|
React에서 입력값의 유효성 검사와 에러 메시지 출력하기 (0) | 2023.07.04 |
useRef (0) | 2023.04.07 |
props (0) | 2023.01.23 |
useState 자세하게 알아보기 (0) | 2023.01.11 |