react native 触摸的响应方法以及过程(一)

本文介绍如何使用React Native中的PanResponder实现触摸手势响应。通过详细示例代码,展示如何配置手势响应逻辑并将其应用于View组件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先需要导入PanResponder

import {
    PanResponder
} from 'react-native';

2、在组件挂载的时候,注册某一变量称为响应者

componentWillMount: function () {
    this.console("componentWillMount===controlType:" + this.props.controlType + ";connectSTBToken:" + JSON.stringify(this.props.connectSTBToken));
    this._panResponder = PanResponder.create({
        // 要求成为响应者:
        onStartShouldSetPanResponder: (evt, gestureState) => true,
        onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
        onMoveShouldSetPanResponder: (evt, gestureState) => true,
        onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

        onPanResponderGrant: (evt, gestureState) => {
            // 开始手势操作。给用户一些视觉反馈,让他们知道发生了什么事情!
            // gestureState.{x,y}0 现在会被设置为0
            this.movePos = [];
            this.console("touch start===X:" + gestureState.x0 + "===Y:" + gestureState.y0);
            this.movePos.push(Math.floor(gestureState.x0), Math.floor(gestureState.y0));
        },
        onPanResponderMove: (evt, gestureState) => {
            // 最近一次的移动距离为gestureState.move{X,Y}
            // 从成为响应者开始时的累计手势移动距离为gestureState.d{x,y}
        },
        onPanResponderTerminationRequest: (evt, gestureState) => true,
        onPanResponderRelease: (evt, gestureState) => {
            // 用户放开了所有的触摸点,且此时视图已经成为了响应者。
            // 一般来说这意味着一个手势操作已经成功完成。
            this.console("touch end===moveX:" + gestureState.moveX + "===moveY:" + gestureState.moveY);
            this.movePos.push(Math.floor(gestureState.moveX), Math.floor(gestureState.moveY));
            this.moveActionEnd(this.movePos);
        },
        onPanResponderTerminate: (evt, gestureState) => {
            // 另一个组件已经成为了新的响应者,所以当前手势将被取消。
            this.console("what???");
        },
        onShouldBlockNativeResponder: (evt, gestureState) => {
            // 返回一个布尔值,决定当前组件是否应该阻止原生组件成为JS响应者
            // 默认返回true。目前暂时只支持android。
            return true;
        }
    });
}

3、定义某个View组件称为手势响应区域

render: function () {
    let keyBoardImg = this.keyBoardImg();
    return (
        <View style={styles.wrap}>
            <View style={[styles.touchContainer, {backgroundColor: '#e2eaea'}]}
                {...this._panResponder.panHandlers}>
                <Animated.Image
                    style={[styles.middleContainer_BG, {opacity: this.bounceValue}]}
                    source={{uri: keyBoardImg}}/>
            </View>
        </View>
    );
}

该示例代码为触摸遥控器解决方案的一部分代码,完整示例代码将会在react native触摸遥控器解决方案提供。

react native 触摸的响应方法以及过程(二)——动画的响应方法及过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值