๊ฐœ๋ฐœ ๐Ÿพ/ReactJS

๋ฆฌ์•กํŠธ์—์„œ setInterval์„ ์‚ฌ์šฉํ•˜์—ฌ ํƒ€์ดํ•‘ ํšจ๊ณผ ์ฃผ๊ธฐ

JOTOKKI 2021. 6. 18. 16:12
728x90

๋ฆฌ์•กํŠธ์—์„œ ํƒ€์ดํ•‘ ํšจ๊ณผ๋ฅผ ์ฃผ๊ณ  ์‹ถ์–ด ์•Œ์•„ ๋ณด์•˜๋”๋‹ˆ react-typing-effect๊ณผ ๊ฐ™์€ ์—ฌ๋Ÿฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ฐ€ ์žˆ์—ˆ๋Š”๋ฐ, 

์ €๋Š” ์ข€ ๋” ์ธ๊ณต์ง€๋Šฅ ์Šคํ”ผ์ปค๊ฐ€ ๋งํ•˜๋Š” ๋Š๋‚Œ์„ ์ฃผ๊ณ  ์‹ถ๊ธฐ๋„ ํ–ˆ๊ณ , 

๊ตฌํ˜„ํ•˜๊ธฐ ์–ด๋ ต์ง€ ์•Š์„ ๊ฒƒ ๊ฐ™์•„์„œ ๋งŒ๋“ค์–ด ๋ณด์•˜์Šต๋‹ˆ๋‹ค. 

 

๊ธฐ๋Šฅ

1. ๋ฟŒ๋ฆด ํ…์ŠคํŠธ ์ค€๋น„ 

2. ๋ฟŒ๋ฆด ํ…์ŠคํŠธ (state)

3. ํ…์ŠคํŠธ ๊ธธ์ด ์ฒดํฌ (state)

 

import React, { useState, useEffect } from 'react'

const TypingText = () => {
  const txt = "์˜ค๋Š˜์€ ๋ญ ๋จน์ง€?";
  const [Text, setText] = useState('');
  const [Count, setCount] = useState(0);
  
  return (
  	<p className="text" >{ Text }</p>
  )
}

export default TypingText

 

render ๋˜์ž ๋งˆ์ž Text state ์•ˆ์— text ์˜ ๋ฌธ์ž์—ด์„ ํ•˜๋‚˜์”ฉ setState ํ•˜์˜€์Šต๋‹ˆ๋‹ค. 

๋ฌธ์ž์—ด ๊ธธ์ด๋Š” Text.length๋กœ ๋น„๊ตํ•ด๋„ ์ƒ๊ด€ ์—†์ง€๋งŒ, ์ €๋Š” Count state๋ฅผ ๋”ฐ๋กœ ๋‘์—ˆ์Šต๋‹ˆ๋‹ค.

useEffect(() => {
    const interval = setInterval(() => {
        setText(Text + txt[Count]); // ์ด์ „ setํ•œ ๋ฌธ์ž + ๋‹ค์Œ ๋ฌธ์ž
        setCount(Count + 1); // ๊ฐœ์ˆ˜ ๋งŒํผ ์ฒดํฌ 
    }, 100);
    if(Count === txt.length)  {  // Count๋ฅผ ๋”ฐ๋กœ ๋‘์ง€ ์•Š๊ณ  Text.length ์ฒดํฌ๋„ ๊ฐ€๋Šฅ
        clearInterval(interval); // ๋ฌธ์ž์—ด ์ฒดํฌ๋ฅผ ํ†ตํ•ด setInterval์„ ํ•ด์ œํ•ฉ๋‹ˆ๋‹ค
    }
    return () => clearInterval(interval); // ์–ธ๋งˆ์šดํŠธ์‹œ setInterval์„ ํ•ด์ œํ•ฉ๋‹ˆ๋‹ค
})

 

๊ฒฐ๊ณผ

์ ์šฉ๋œ ํ™”๋ฉด

clear ํ•˜๋Š” ์‹œ์ ์ด ๊ธ€์ž๋ฅผ ๋ชจ๋‘ ์ถœ๋ ฅํ•œ ์‹œ์ ์ด๋ฏ€๋กœ,

์ดํ›„ ์•ก์…˜ ์ฒ˜๋ฆฌ๋„ ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

 

{ ... }
const [Color, setColor] = useState('black');

const handleAfterAction = () => {
  setColor('orange');
}


useEffect(() => {
  { ... }
  if (Text.length === txt.length) {
  	clearInterval(interval);
  	handleAfterAction(); // ๊ธ€์ž๊ฐ€ ๋ชจ๋‘ ์ถœ๋ ฅ๋œ ํ›„ handleAfterAction ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.
  }
  return () => clearInterval(interval);
});

return (
  <div className="App">
    <p className="text" style={{color: Color}}>{Text}</p>
  </div>
);

๊ฒฐ๊ณผ

์ ์šฉ๋œ ํ™”๋ฉด

 

 

๋ฐ˜์‘ํ˜•