0 -> 100 을 만드는 건데
1. AnimatedBox를 만들고
2. AnimatedBox에 움직이는 설정을 style={{transform: [ {translateY: Y}]}} 로
3. 그 Y의 기초값 0은 const Y = new Animated.Value(0) 이며
4. 그 Y의 마지막 값은 버튼을 눌렀을 경우 (moveUp), Animated.timing(Y, {toValue: 100}).start() 가 됨
5. Animated(Y, {}).start(toggleUp)으로 반복적으로 움직이게 하는 부분 또한 중요하다
6. toggle은 toggleUp=()=>setUp(prev => !prev) 로 true->false->true로 만든다.
npm i styled-components
npm install @types/styled-components @types/styled-components-react-native
import styled from 'styled-components/native'
visualCode에서 플러그인도 다운 받아서 사용해야 함.
react-naitve 컨테이너 사용방법
const Container = styled.View`
flex: 1;
justify-content: center;
align-items: center;
`
import { Animated} from 'react-native';
에니메이션 사용할 컴포넌트 지정해주기
const Box = styled.View`
background-color: tomato;
width: 200px;
height: 200px;
`
const AnimatedBox = Animated.createAnimatedComponent(Box)
return(
<Container>
<TouchableOpacity onPress={moveUp}>
<AnimatedBox style={{
transform: [
{translateY: Y}
]
}} />
</TouchableOpacity>
</Container>
)
transform: {translateY: Y} Y 이동하기
const Y = useRef(new Animated.Value(0)).current //리렌더 되어도 초기값으로 다시 가지 않음.
useRef().current 를 사용하면서 리렌더링이 일어나도 마지막값을 계속 가져갈 수가 있음.
new Animated.Value(0) 값을 쓰면서 useState가 아니니 에니메이션 값을 사용이 가능함.
Anmiated.timing(Y, {}).start()
const moveUp = () => {
Animated.timing(Y, {
toValue: up ? 100 : -100,
duration: 400,
bounciness: 20,
easing: Easing.elastic(10),
useNativeDriver: true
}).start(toggleUp)
}
moveUp() 함수를 실행을 시키면 움직이는 박스의 설정을 위 처럼해둔다.
Y 함수가 0에서 100까지 올라갔다가, 다시 100에서 -100, 그리고 -100에서 100까지 왔다갔다 하는 박스 설정이다.
전체 코드
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components/native'
import { Animated, Easing, TouchableOpacity } from 'react-native';
const Container = styled.View`
flex: 1;
justify-content: center;
align-items: center;
`
const Box = styled.View`
background-color: tomato;
width: 200px;
height: 200px;
`
const AnimatedBox = Animated.createAnimatedComponent(Box)
export default function App() {
const [up, setUp] = useState(false)
const Y = useRef(new Animated.Value(0)).current //리렌더 되어도 초기값으로 다시 가지 않음.
const toggleUp = () => setUp(prev => !prev)
Y.addListener(()=>console.log("Y", Y))
const moveUp = () => {
Animated.timing(Y, {
toValue: up ? 100 : -100,
duration: 400,
bounciness: 20,
easing: Easing.elastic(10),
useNativeDriver: true
}).start(toggleUp)
}
return(
<Container>
<TouchableOpacity onPress={moveUp}>
<AnimatedBox style={{
transform: [
{translateY: Y}
]
}} />
</TouchableOpacity>
</Container>
)
}