일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- classList toggle
- 커스텀훅
- 대표님물리기없기
- 방심은금물
- 를
- 간식금지다!
- 포트폴리오
- 언젠간가겠지
- 2020
- className
- 리엑트할수있는퍼블리셔라규
- 내배위의고양이
- 냥빨이다가온다
- new set()
- 클래스 토글
- classList
- windowwidth
- react-router
- classList remove
- set()
- 안짤렸다
- classList add
- 퍼블리싱
- chart.js
- 배열중복제거
- 접근성
- ROUTER 버전6
- react-router-dom
- chart responsive
- react
Archives
- Today
- Total
틈
[REACT] useImperativeHandle, forwardRef hook 본문
자식 컴포넌트의 ref 값을 부모 컴포넌트에서 사용하기 위해 고안한 훅인듯 하다.
[부모 컴포넌트]
function App() {
const audioRef = useRef();
const onPlay = () => {
audioRef.current.play();
};
return (
<div className="App">
<div className="container">
<ProgressArea ref={audioRef} />
</div>
</div>
);
}
[자식 컴포넌트]
import React, { useRef,useImperativeHandle, forwardRef } from 'react';
function ProgressArea(props, ref) {
const audio = useRef();
useImperativeHandle(ref, () => ({
play: () => {
audio.current.play();
},
}));
return (
<audio
autoPlay
ref={audio}
src={music1}
></audio>
);
}
export default forwardRef(ProgressArea);
부모 컴포넌트에서 ref를 선언하고,
자식 컴포넌트에 props로 (props,ref)를 받아서
useImperativeHandle에 ref를 인자로 받고, 메서드로 처리한다.
마지막에 export할때는 forwardRef로 내보내야 한다.
useImperativeHandle과 forwardRef는 짝꿍이다.
다만, 리엑트에서는 ref사용을 권장하지 않으므로, redux,contextAPI등을 활용하는 것이 좋다.
(소소하게만 사용해야겠다.)
'code > React.js' 카테고리의 다른 글
[REACT] kakao지도 (0) | 2022.06.02 |
---|---|
[REACT] 외부 API 받아오기(with typescript) -declare (0) | 2022.06.01 |
[REACT] react 설치 방법 변경 (0) | 2022.05.13 |
[REACT] 유용한 dependencies (0) | 2022.05.07 |
[REACT] input[type=file] 파일 이름 받아오기 (0) | 2022.05.07 |
Comments