๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • ์žฅ์›์ต ๊ธฐ์ˆ ๋ธ”๋กœ๊ทธ
๐Ÿ“บ Front End/- React, Next.js

[React-Spring ๊ณต์‹ ๋ฌธ์„œ๋กœ ๋ฐฐ์šฐ๊ธฐ] useSpring

by Wonit 2020. 11. 4.

ํ˜„์žฌ React-Spring์—๋Š” 5๊ฐ€์ง€ Hook์ด ์žˆ๋‹ค.

  • useSpring : Data๋ฅผ a ์—์„œ b๋กœ ์ด๋™์‹œํ‚ค๋Š” ๋‹จ์ผ Spring์ด๋‹ค.
  • useSprings : ๋‹ค์ค‘ Spring์œผ๋กœ List์™€ ๊ฐ™์ด ๊ฐ๊ฐ์˜ Spring์ด ์›€์ง์ด๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค๋ฃฐ ๋•Œ ์‚ฌ์šฉ๋œ๋‹ค.
  • useTrail : ํ•˜๋‚˜์˜ ๋ฐ์ดํ„ฐ์…‹์œผ๋กœ ๋‹ค์ค‘ Springs์„ ๊ตฌ๋™์‹œํ‚ค๋ฉฐ, Spring์€ ๊ทธ๋ฅผ ๋”ฐ๋ฅด๊ฑฐ๋‚˜ ๋‹ค๋ฅธ ๊ฒƒ๋“ค์„ ์ด๋ˆ๋‹ค.
  • useTransition : mount/unmount๋ฅผ ๋‹ค๋ฃฌ๋‹ค.
  • useChain : ๋‹ค๋Ÿ‰์˜ ์• ๋‹ˆ๋ฉ”์ด์…˜์„ ํ•จ๊ป˜ ๋™๋ฐ˜ํ•  ๋•Œ ์‚ฌ์šฉ๋œ๋‹ค.

useSpring

๊ฐ€์žฅ ์‰ฌ์šด ๊ฒƒ์€ useSpring์ด๋‹ค.


ํ•˜์ง€๋งŒ ๋‹ค๋ฅธ ๊ฒƒ๋“ค๋„ ์ด useSpring์— ๊ธฐ๋ฐ˜ํ•œ ๋™์ž‘์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ค‘์š”ํ•˜๋‹ค.

import {useSpring, animated} from 'react-spring'

function App() {
  const props = useSpring({opacity: 1, from: {opacity: 0}})
  return (
      <>
        <h1>React Spring์˜ ์ž…๋ฌธ</h1>
          <animated.div style={props}>I will fade in</animated.div>
    </>
  )
}

๊ณผ ๊ฐ™์ด ์‚ฌ์šฉ๋  ์ˆ˜ ์žˆ๋Š”๋ฐ, ์ฐจ๊ทผ์ฐจ๊ทผ ๋‹จ๊ณ„๋กœ ์•Œ์•„๋ณด์ž.

import

import {useSpring, animated} from "react-spring";

props ๋„˜๊ธฐ๋Š” ๋ฐฉ๋ฒ• (์—…๋ฐ์ดํŠธ ๋ฐฉ๋ฒ•)

animated-values๋ฅผ ๋„˜๊ธฐ๋Š” ๋ฐฉ๋ฒ•์—๋Š” 3๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค.

  1. ๊ฐ’ ๋ฎ์–ด์“ฐ๊ธฐ
  2. ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜ ๋„˜๊ธฐ๊ธฐ
  3. ์• ๋‹ˆ๋ฉ”์ด์…˜ props๋กœ ์ „๋‹ฌํ•˜๊ธฐ.

๊ฐ’ ๋ฎ์–ด์“ฐ๊ธฐ

const props = useSpring({opactiy: toggle ? 1: 0})

๋งŒ์•ฝ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณ€๊ฒฝ๋œ props๋ฅผ ํ†ตํ•ด re-render ํ•œ๋‹ค๋ฉด animation์€ ์—…๋ฐ์ดํŠธ ๋œใ„ท.

ํ•จ์ˆ˜ ๋„˜๊ธฐ๊ธฐ

const [props, set, stop] = useSpring(() => ({opacity: 1}))
set({opacity: toggle ? 1 : 0})
stop()

value๋ฅผ return ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌํ•˜๊ณ  set์„ ์ด์šฉํ•ด์„œ ์—…๋ฐ์ดํŠธ ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ๊ตฌ์„ฑํ•˜๋ฉด ์œ„์˜ ๋ฐฉ๋ฒ•์ฒ˜๋Ÿผ ๋ Œ๋”๋ง๋˜์ง€ ์•Š๋Š”๋‹ค. (๋ Œ๋”๋ง ๋˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์†Œ๋ฆฌ๊ฐ€ ์• ๋‹ˆ๋ฉ”์ด์…˜์ด ์‹คํ–‰๋˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์†Œ๋ฆฌ๋Š” ์•„๋‹˜)

 

์ด์™€ ๊ฐ™์€ ์—…๋ฐ์ดํŠธใ…กใ„น ์ฒ˜๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ๋น ๋ฅด๊ฒŒ ๋ฐœ์ƒํ•˜๋Š” ์—…๋ฐ์ดํŠธ์— ์œ ์šฉํ•˜๊ณ  ์ด๋ฅผ ์„ ํ˜ธํ•ด์•ผ ํ•œ๋‹ค๊ณ  ํ•œ๋‹ค.

 

์„ ํƒ์ ์œผ๋กœ stop()ํ•จ์ˆ˜์™€ ๊ฐ™์€ ์ •์ง€ ํ•จ์ˆ˜๊ฐ€ ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

props ์ด์šฉํ•˜๊ธฐ

return <animated.div style={props}>I WILL FADE</animated.div>

๋Œ“๊ธ€