React์์ focus, text selection, media playback, ์ ๋๋ฉ์ด์
์ ์ฉ, jd.js ๋ฐ greensock ๋ฑ DOM ๊ธฐ๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ํ์ฉ๊ณผ ๊ฐ์ด DOM ์๋ฆฌ๋ฉํธ์ ์ฃผ์๊ฐ์ ํ์ฉํด์ผ ํ๋ ๊ฒฝ์ฐ์ ์ฌ์ฉํ๋ hook ํจ์๋ก, useRef
๋ฅผ ์ฌ์ฉํด DOM ๋
ธ๋, element, React ์ปดํฌ๋ํธ ์ฃผ์๊ฐ์ ์ฐธ๊ณ ํ ์ ์๋ค. ๋ํ ์ด ์ฃผ์๊ฐ์ ์ปดํฌ๋ํธ๊ฐ re-render ๋๋๋ผ๋ ๋ฐ๋์ง ์๋๋ค.
์์ ๋ช ์๋ ์์ธ์ ์ธ ์ํฉ์ ์ ์ธํ ๋๋ถ๋ถ์ ๊ฒฝ์ฐ, useRef๋ฅผ ๋จ์ฉํ๋ ๊ฒ์ ๋ถ์ ์ ํ๋ค.
// const refContainer = useRef(initialValue);
const ์ฃผ์๊ฐ์_๋ด๋_๋ณ์ = useRef(์ฐธ์กฐ์๋ฃํ)
// ์ฃผ์๊ฐ์_๋ด๋_๋ณ์์ ์ด๋ค ์ฃผ์๊ฐ์ด๋ ๋ด์ ์ ์๋ค.
return (
<div>
<input ref={์ฃผ์๊ฐ์_๋ด๋_๋ณ์} type="text" />
{/* React์์ ์ฌ์ฉ ๊ฐ๋ฅํ ref๋ผ๋ ์์ฑ์ ์ฃผ์๊ฐ์_๋ด๋_๋ณ์๋ฅผ ๊ฐ์ผ๋ก ํ ๋นํ๋ฉด*/}
{/* ์ฃผ์๊ฐ์_๋ด๋_๋ณ์์๋ input DOM ์๋ฆฌ๋จผํธ์ ์ฃผ์๊ฐ ๋ด๊น. */}
{/* ์ดํ, ๋ค๋ฅธ ์ปดํฌ๋ํธ์์ input DOM ์๋ฆฌ๋จผํธ๋ฅผ ํ์ฉํ ์ ์๋ค. */}
</div>);
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
import React, { useRef } from "react";
const Focus = () => {
const firstRef = useRef(null);
const secondRef = useRef(null);
const thirdRef = useRef(null);
const handleInput = (event) => {
console.log(event.key, event);
if (event.key === "Enter") {
if (event.target === firstRef.current) {
secondRef.current.focus();
event.target.value = "";
} else if (event.target === secondRef.current) {
thirdRef.current.focus();
event.target.value = "";
} else if (event.target === thirdRef.current) {
firstRef.current.focus();
event.target.value = "";
} else {
return;
}
}
};
return (
<div>
<h1>focus ์์ </h1>
<h3>๊ฐ ๋น์นธ์ ๋จ์ด ์
๋ ฅ ํ enter ๋๋ฅผ ์, focus๊ฐ ๋ค์ ๋น์นธ์ผ๋ก ์ด๋ํ๋ค.</h3>
<div>
<label>์ฒซ ๋ฒ์งธ ๋น์นธ์ text ์
๋ ฅ ํ, enter ๋๋ฅผ ์, ๋ ๋ฒ์งธ ๋น์นธ์ผ๋ก focus ์ด๋</label>
<input ref={firstRef} onKeyUp={handleInput} />
</div>
<div>
<label>๋ ๋ฒ์งธ ๋น์นธ์ text ์
๋ ฅ ํ, enter ๋๋ฅผ ์, ์ธ ๋ฒ์งธ ๋น์นธ์ผ๋ก focus ์ด๋</label>
<input ref={secondRef} onKeyUp={handleInput} />
</div>
<div>
<label>์ธ ๋ฒ์งธ ๋น์นธ์ text ์
๋ ฅ ํ, enter ๋๋ฅผ ์, ์ฒซ ๋ฒ์งธ ๋น์นธ์ผ๋ก focus ์ด๋</label>
<input ref={thirdRef} onKeyUp={handleInput} />
</div>
</div>
);
};
export default Focus;
import { useRef } from "react";
export default function App() {
const videoRef = useRef(null);
const playVideo = () => {
videoRef.current.play();
console.log(videoRef.current);
};
const pauseVideo = () => {
videoRef.current.pause();
};
const RemoveVideo = () => {
videoRef.current.remove();
}
return (
<div className="App">
<div>
<button onClick={playVideo}>Play</button>
<button onClick={pauseVideo}>Pause</button>
<button onClick={RemoveVideo}>Remove</button>
</div>
<video ref={videoRef} width="320" height="240" controls>
<source
type="video/mp4"
src="https://player.vimeo.com/external/544643152.sd.mp4?s=7dbf132a4774254dde51f4f9baabbd92f6941282&profile_id=165"
/>
</video>
</div>
);
}
Reference: ์ฝ๋์คํ ์ด์ธ