점 여러개가 색이 하나씩 순차적으로 바뀌는 효과
채팅같은거 칠 때 흔히 볼 수 있음.
// DotAnimation.js import React, { useEffect, useState } from 'react'; import { StyleSheet, Animated } from 'react-native'; import Dot from './Dot'; const DotAnimation = () => { return ( <Animated.View style={styles.wrapper}> <Dot marginRight={7}/> <Dot marginRight={7} delay={600}/> <Dot delay={1200}/> </Animated.View> ); }; const styles = StyleSheet.create({ wrapper: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 77, height: 36 } }); export default DotAnimation;
애니메이션 효과를 담을 container.
Dot component
에marginRight
값과delay
값을 넘겨준다.
// Dot.js import React, { useState, useEffect } from "react"; import { Animated, StyleSheet } from "react-native"; const Dot = ({ marginRight = 0, delay = 0 }) => { const [dotColor, setDotColor] = useState(new Animated.Value(0)); useEffect(() => { Animated.sequence([ Animated.delay(delay), Animated.loop( Animated.timing(dotColor, { toValue: 1, duration: 3000 }) ) ]).start(); }, []); const dotInterpolate = dotColor.interpolate({ inputRange: [0, .1, .9, 1], outputRange: ['rgb(170, 170, 170)', 'rgb(230, 230, 230)', 'rgb(230, 230, 230)', 'rgb(170, 170, 170)'] }); return ( <Animated.View style={[styles.dot, { backgroundColor: dotInterpolate, marginRight: marginRight }]}></Animated.View> ); }; const styles = StyleSheet.create({ dot: { width: 4, height: 4, borderRadius: 2 } }); export default Dot;
애니메이션 효과를 줘야하는 부분이 점의 색이다.
Animated.loop()
를 이용해 점의 색이 바뀌는걸 계속 반복할 것이다.그런데 점들은 순차적으로 색이 바뀌어야 하니
useEffect
에서props
로 받은delay
값을 이용해Animated.delay()
로 딜레이를 걸어준다.
Animated.delay()
와Animated.loop()
가 순차적으로 발생해야 되서Animated.sequence()
로 묶어준다.처음에
delay
를Animated.timing()
에 넣었다가 색 바뀌는 타이밍이 뒤죽박죽이어서 뭔가 했더니 그 딜레이 값을 처음에만 적용하는게 아니라 지속적으로 딜레이값을 적용시키는 것이었다.그래서 지금과 같이 처음에만
Animated.delay()
로 지연시키고, 그 다음부터는 딜레이와 상관없이Animated.loop()
가 계속 애니메이션을 순환시킨다.그리고 점의 색이 변하는 타이밍은
interpolate
를 사용해 타이밍을 잡아준다.