【React-Native】自定义Vant--Drawer(抽屉)动画组件
import React, { useRef, useEffect } from 'react';
import { Animated, View, StyleSheet, Dimensions, Platform } from 'react-native';
import { useMount, useUnmount } from 'react-native-hooks';
import { noop } from '../../utils';
const { width: deviceWidth } = Dimensions.get('window');
export default ({
visible = false,
position = 'left',
drawerStyle,
drawerContent,
onClose = noop,
}) => {
const drawerAnimatedValue = useRef(new Animated.Value(0)).current;
const isRight = position === 'right';
const offsetValue = isRight ? deviceWidth : -deviceWidth;
const openDrawer = () => {
Animated.spring(drawerAnimatedValue, {
toValue: 1,
useNativeDriver: true,
}).start();
};
const closeDrawer = () => {
Animated.spring(drawerAnimatedValue, {
toValue: 0,
useNativeDriver: true,
}).start(() => onClose());
};
useMount(() => {
if (visible) {
openDrawer();
}
});
useUnmount(() => {
closeDrawer();
});
const translateX = drawerAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [offsetValue, 0],
});
const transform = [{ translateX }];
if (Platform.OS === 'android') {
transform.push({ scale: drawerAnimatedValue });
}
return (
<Animated.View style={[styles.drawer, drawerStyle, { transform }]}>
{drawerContent()}
</Animated.View>
);
};
const styles = StyleSheet.create({
drawer: {
width: deviceWidth,
position: 'absolute',
top: 0,
backgroundColor: 'white',
},
});
这段代码实现了一个简单的Vant--Drawer组件,它使用React Native的Animated API来实现动画效果。代码中定义了openDrawer
和closeDrawer
函数来控制抽屉的打开和关闭,并使用了useMount
和useUnmount
钩子来处理组件挂载和卸载时的逻辑。此外,代码还处理了平台特有的样式差异,确保抽屉在Android和iOS上的表现一致。
评论已关闭