useRef로 특정DOM 선택하기
import React,{useState, useRef} from 'react';
function InputSample(){
const [inputs, setInputs] = useState({
name : '',
nickname : ''
});
const nameInput = useRef();
// useRef를 호출한다
const {name, nickname} = inputs;
const onChange = (e) => {
const {name, value} = e.target;
setInputs({
...inputs,
[name]: value,
});
};
const onReset = () => {
setInputs({
name: '',
nickname: ''
});
nameInput.current.focus();
// 해당 DOM을 선택할 때 nameInput.current.을 사용한다
}
return(
<div>
<input
name='name'
placeholder="이름"
onChange={onChange}
value={name}
ref={nameInput}
// 원하는 돔에 ref 설정을 해준다
/>
<input
name='nickname'
placeholder="닉네임"
onChange={onChange}
value={nickname}
/>
<button onClick={onReset}>초기화</button>
<div>
<b>값: </b>
{name} ({nickname})
</div>
</div>
)
}
export default InputSample;