react native 悬浮客服可拖动

2023-11-13  本文已影响0人  王宣成
import React, { useRef } from 'react';
import { View, Image, TouchableOpacity, StyleSheet, PanResponder, Animated } from 'react-native';
import { useNavigation, useFocusEffect } from '@react-navigation/native';

const DraggableButton = () => {
    const navigation = useNavigation();
    const goToCustomerScreen = () => {
        navigation.navigate('Customer');
    }

    const pan = useRef(new Animated.ValueXY()).current;

    const panResponder = useRef(
        PanResponder.create({
            onMoveShouldSetPanResponder: () => true,
            onPanResponderGrant: () => {
                pan.setOffset({
                    x: pan.x._value,
                    y: pan.y._value
                });
            },
            onPanResponderMove: Animated.event(
                [
                    null,
                    {dx: pan.x, dy: pan.y}
                ],
                {useNativeDriver: false}
            ),
            onPanResponderRelease: () => {
                pan.flattenOffset();
            }
        })
    ).current;
    

    return (
        <Animated.View
            style={[
                styles.container,
                {
                    transform: [{ translateX: pan.x }, { translateY: pan.y }],
                },
            ]}
            {...panResponder.panHandlers}
        >
            <TouchableOpacity style={styles.button} onPress={goToCustomerScreen}>
                <Image style={styles.image} source={require('../../assets/imgs/tabs/customer_select.png')} />
            </TouchableOpacity>
        </Animated.View>
    );
};

const styles = StyleSheet.create({
    container: {
        position: 'absolute',
        right: 20,
        bottom: 100,
        zIndex: 1,
    },
    button: {
        width: 40,
        height: 40,
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 25,
    },
    image: {
        width: 38,
        height: 38,
    },
});

export default DraggableButton;
上一篇下一篇

猜你喜欢

热点阅读