|
| 1 | +import * as React from "react"; |
| 2 | +import { |
| 3 | + Animated, |
| 4 | + ViewStyle, |
| 5 | + StyleProp, |
| 6 | + Pressable, |
| 7 | + PressableProps, |
| 8 | +} from "react-native"; |
| 9 | +const AnimatedPressable = Animated.createAnimatedComponent(Pressable); |
| 10 | + |
| 11 | +type CustomStyleProp = StyleProp<ViewStyle> | Array<StyleProp<ViewStyle>>; |
| 12 | +export interface IRNBounceableProps extends PressableProps { |
| 13 | + onPress?: () => void; |
| 14 | + bounceEffectIn?: number; |
| 15 | + bounceEffectOut?: number; |
| 16 | + bounceVelocityIn?: number; |
| 17 | + bounceVelocityOut?: number; |
| 18 | + bouncinessIn?: number; |
| 19 | + bouncinessOut?: number; |
| 20 | + useNativeDriver?: boolean; |
| 21 | + children?: React.ReactNode; |
| 22 | + style?: CustomStyleProp; |
| 23 | +} |
| 24 | + |
| 25 | +interface IState { |
| 26 | + bounceValue: any; |
| 27 | +} |
| 28 | + |
| 29 | +export default class RNBounceable extends React.Component< |
| 30 | + IRNBounceableProps, |
| 31 | + IState |
| 32 | +> { |
| 33 | + constructor(props: IRNBounceableProps) { |
| 34 | + super(props); |
| 35 | + this.state = { |
| 36 | + bounceValue: new Animated.Value(1), |
| 37 | + }; |
| 38 | + } |
| 39 | + |
| 40 | + bounceAnimation = (value: number, velocity: number, bounciness: number) => { |
| 41 | + const { useNativeDriver = true } = this.props; |
| 42 | + Animated.spring(this.state.bounceValue, { |
| 43 | + toValue: value, |
| 44 | + velocity, |
| 45 | + bounciness, |
| 46 | + useNativeDriver, |
| 47 | + }).start(); |
| 48 | + }; |
| 49 | + |
| 50 | + render() { |
| 51 | + const { |
| 52 | + bounceEffectIn = 0.93, |
| 53 | + bounceEffectOut = 1, |
| 54 | + bounceVelocityIn = 0.1, |
| 55 | + bounceVelocityOut = 0.4, |
| 56 | + bouncinessIn = 0, |
| 57 | + bouncinessOut = 0, |
| 58 | + children, |
| 59 | + style, |
| 60 | + onPress, |
| 61 | + } = this.props; |
| 62 | + return ( |
| 63 | + <AnimatedPressable |
| 64 | + {...this.props} |
| 65 | + style={[{ transform: [{ scale: this.state.bounceValue }] }, style]} |
| 66 | + onPressIn={() => { |
| 67 | + this.bounceAnimation(bounceEffectIn, bounceVelocityIn, bouncinessIn); |
| 68 | + }} |
| 69 | + onPressOut={() => { |
| 70 | + this.bounceAnimation( |
| 71 | + bounceEffectOut, |
| 72 | + bounceVelocityOut, |
| 73 | + bouncinessOut, |
| 74 | + ); |
| 75 | + }} |
| 76 | + onPress={onPress} |
| 77 | + > |
| 78 | + {children} |
| 79 | + </AnimatedPressable> |
| 80 | + ); |
| 81 | + } |
| 82 | +} |
0 commit comments