useRef 검색 그마안
사실 자주 쓰지않고 특정상황에서만 쓰다보니 검색을 자주하게 되는데 이제 검색 그만하고 이거 보고 끝내려고 작성
재랜더링 하지 않고 컴포넌트의 속성만 조회, 수정 하는 아이이며 dom을 직접적으로 선택하는 아이이다.
import React, { useState, useRef } from 'react';
function InputTest() {
const [inputs, setInputs] = useState({
name: '',
nickname: ''
});
const nameInput = useRef(); //ref객체 만들기
const { name, nickname } = inputs; // 비구조화 할당
const onChange = e => {
setText(e.target.value)
};
const onReset = () => {
setText('');
nameInput.current.focus();
};
const onReset = () => {
setInputs({
name: '',
nickname: '',
});
nameInput.current.focus(); //이렇게 접근
};
return (
<div>
<input
name="name"
onChange={onChange}
value={name}
ref={nameInput} //선택하고 싶은 dom에 속성으로 ref 값을 설정
/>
<button onClick={onReset}>초기화</button>
<div>
{name}
</div>
</div>
);
}
export default InputTest;
위 처럼 값을 여러개 입력하고 첫 번째 칸으로 이동해야하는 경우 필요할 수 있다.
const RSPfunction = () => {
const [result, setResult] = useState('');
const [imgCoord, setImgCoord] = useState(rspCoords.바위);
const [score, setScore] = useState(0);
const interval = useRef();
useEffect(() => {
interval.current = setInterval(changeHand, 100);
return () => {
clearInterval(interval.current);
}
}, [imgCoord]);
카운트나 페이지, 타이머 등 값을 0으로 초기화 할 필요가 있을 경우
import React, { useRef } from 'react';
import UserList from './UserList';
function App() {
const users = [
{
id: 1,
username: '라이언',
},
{
id: 2,
username: '춘식',
},
{
id: 3,
username: '무지',
}
];
const nextId = useRef(4);
const onCreate = () => {
배열에 새로운 항목을 추가하는 로직 / id: nextId.current (오퍼레이트 setState나 push나 등등)
nextId.current += 1; //배열 수정해주고 현재 nextId를 1추가하여 5로 만들어주기
};
return <UserList users={users} />;
}
export default App;