useRef

๊น€๋‚จ๊ฒฝยท2022๋…„ 12์›” 26์ผ

react

๋ชฉ๋ก ๋ณด๊ธฐ
15/37

์˜๋ฏธ

๐Ÿ’ก DOM ์—˜๋ฆฌ๋จผํŠธ ์ฃผ์†Œ๊ฐ’์„ ํ™œ์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ
(focus, media play ๋“ฑ)

ํŠน์ง•

๐Ÿ’ก ์ปดํฌ๋„ŒํŠธ๊ฐ€ Re-render๋˜์–ด๋„ ๋ฐ”๋€Œ์ง€ ์•Š์Œ
๐Ÿ’ก ๋ฆฌ์—‘ํŠธ๋Š” ์„ ์–ธํ˜• ํ”„๋กœ๊ทธ๋žจ ์›์น™์„ ๋”ฐ๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ๋ถ€๋“์ดํ•œ ์ƒํ™ฉ์—์„œ๋งŒ ์‚ฌ์šฉ

์‚ฌ์šฉ์˜ˆ์‹œ

๐Ÿ“— focus

import { useRef } from "react";

function x(){
	const inputEl = useRef(null);
  	const handleClick = () => {
    	inputEl.current.focus();
    };
  
  	return (
    	<>
        	<input ref={inputEl} type="text"/>
        	<button onClick={handleClick}>a</button>
        </>
    );
}

๐Ÿ“— video

import { useRef } from "react";

function x(){
	const videoEl = useRef(null);
  	const handlePlay = () => {
    	videoEl.current.play();
    };
  	const handlePause = () => {
    	videoEl.current.pause();
    };
  
  	return (
    	<>
        	<video ref={videoEl} controls/>
        		<source type="video/mp4" src={์˜์ƒ์ฃผ์†Œ} />
        	</video>
        	<button onClick={handlePlay}>play</button>
      		<button onClick={handlePause}>pause</button>
        </>
    );
}
profile
๊ธฐ๋ณธ์— ์ถฉ์‹คํ•˜๋ฉฐ ์•ž์œผ๋กœ ๋ฐœ์ „ํ•˜๋Š”

0๊ฐœ์˜ ๋Œ“๊ธ€