How would you implemen...
How would you implemen...
To implement animations on events in React Native, you can use the Animated
API, which provides a powerful and flexible way to create animations. Here’s a step-by-step guide on how to implement animations on events such as button presses, scrolls, and gestures:
First, you need to create an Animated.Value
that will be used to drive the animation. This value will be updated based on the event.
import React, { useRef } from 'react';
import { View, Animated, TouchableOpacity, Text } from 'react-native';
const MyAnimatedComponent = () => {
const animatedValue = useRef(new Animated.Value(0)).current;
const startAnimation = () => {
Animated.timing(animatedValue, {
toValue: 1,
duration: 500,
useNativeDriver: true,
}).start();
};
return (
<View>
<Animated.View style={{ opacity: animatedValue, width: 100, height: 100, backgroundColor: 'blue' }} />
<TouchableOpacity onPress={startAnimation}>
<Text>Press Me</Text>
</TouchableOpacity>
</View>
);
};
export default MyAnimatedComponent;
To animate a component when a button is pressed, you can use the TouchableOpacity
component to trigger the animation.
const handlePress = () => {
Animated.spring(animatedValue, {
toValue: 1,
friction: 5,
useNativeDriver: true,
}).start();
};
<TouchableOpacity onPress={handlePress}>
<Text>Press Me</Text>
</TouchableOpacity>
To animate components based on scroll events, you can use the Animated.event
function to map the scroll position to an animated value.
const scrollY = useRef(new Animated.Value(0)).current;
<Animated.ScrollView
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
{ useNativeDriver: true }
)}
scrollEventThrottle={16}
>
{/* Scrollable content */}
</Animated.ScrollView>
For gesture-based animations, you can use the react-native-gesture-handler
library in combination with react-native-reanimated
.
import { PanGestureHandler } from 'react-native-gesture-handler';
import { useAnimatedGestureHandler, useSharedValue, useAnimatedStyle } from 'react-native-reanimated';
const pan = useSharedValue({ x: 0, y: 0 });
const gestureHandler = useAnimatedGestureHandler({
onStart: (_, ctx) => {
ctx.startX = pan.value.x;
ctx.startY = pan.value.y;
},
onActive: (event, ctx) => {
pan.value = {
x: ctx.startX + event.translationX,
y: ctx.startY + event.translationY,
};
},
});
const animatedStyle = us...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào