리액트 네이티브에서 애니메이션 효과를 구현하기 위해서 Animated를 사용할 수 있다.
하지만, 이는 숫자 value만 가질 수 있기에 rotate와 같이 문자열을 인자로 받아 애니메이션을 실행하는 경우 작동하지 않는 경우가 있다.
이럴 경우에 react-native-reanimated를 사용하여 애니메이션 효과를 구현할 수 있다.
오늘은 그중에서도 keyframe을 사용하여 회전 효과를 구현해보기로 하였다.
일단, 설치한 뒤 babel 설정을 해준다.
npm install react-native-reanimated
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['react-native-reanimated/plugin'],
};
위와 같이 설정을 하면, react-native-reanimated를 사용할 수 있다.
그리고 공식 문서를 참고하여 다음과 같이 keyframe을 사용할 수 있었다.
import React, {useState} from 'react';
import {Button, StyleSheet, View} from 'react-native';
import Animated, {Easing, Keyframe} from 'react-native-reanimated';
const enteringAnimation = new Keyframe({
0: {
transform: [{rotate: '-45deg'}],
},
50: {
transform: [{rotate: '45deg'}],
},
100: {
transform: [{rotate: '0deg'}],
},
}).duration(2000);
const exitingAnimation = new Keyframe({
0: {
opacity: 1,
transform: [{skewX: '0deg'}],
},
30: {
opacity: 0.5,
transform: [{skewX: '40deg'}],
easing: Easing.exp,
},
100: {
opacity: 0,
transform: [{skewX: '-10deg'}],
},
}).delay(2000);
function RotateText() {
const [isVisible, setIsVisible] = useState(false);
return (
<View>
<Button title="show in/out" onPress={() => setIsVisible(prev => !prev)} />
{isVisible ? (
<Animated.View
entering={enteringAnimation}
style={styles.viewContainer}>
<Animated.Text style={styles.textStyle} exiting={exitingAnimation}>
Test
</Animated.Text>
</Animated.View>
) : null}
</View>
);
}
const styles = StyleSheet.create({
viewContainer: {
borderWidth: 1,
borderColor: 'red',
},
textStyle: {
color: 'red',
fontSize: 25,
},
});
export default RotateText;
react-native-reanimated의 Animated 컴포넌트에서 두 props인 entering, exiting의 keyframe은 각각 렌더링 될 때, 렌더링 된 컴포넌트가 사라질 때 실행된다.
버튼을 눌러 컴포넌트가 렌더링되면, 좌우로 회전하고 다시 버튼을 누르면, 컴포넌트가 서서히 사라진다.
각각 keyframe에 duration으로 애니메이션 시간을 정할 수 있고, delay를 통해서 얼마만큼의 시간이 지난 뒤에 이 애니메이션이 실행될지 설정할 수 있다.
https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation
Installation | React Native Reanimated
Installing Reanimated requires a couple of additional steps compared to installing most of the popular react-native packages.
docs.swmansion.com
https://docs.swmansion.com/react-native-reanimated/docs/api/LayoutAnimations/keyframeAnimations/
Keyframe Animations | React Native Reanimated
The document explains how you can define complex animation using simple and popular animation definitions schema - Keyframes.
docs.swmansion.com
'React Native' 카테고리의 다른 글
React Native 에서 Redux 디버깅하기 (redux-flipper) (0) | 2023.04.19 |
---|---|
React Navigation 중첩 라우팅 구현하기 (0) | 2023.04.16 |
React Native에서 node 내장 라이브러리 사용하기 (rn-nodeify) (0) | 2023.03.11 |
React Navigation 타입스크립트 사용하기 (0) | 2023.02.23 |
React Native 카메라로 QR code 읽어오기 (react-native-vision-camera) (0) | 2023.02.17 |