问题
I am trying to enable panResponder to move a component through the screen in a drag and drop mode. However this drag and drop must be initiated through a longPress
on such element.
longPress
captures the event and so when panResponder
is enabled onStartShouldSetPanResponder => this.state.panEnabled
we need to press again.
I would like to fire a native event, or, else, activate the drag without pressing again. Is it possible to re-emit a native event? Can we pass it to the panResponder in any way?
Thanks!
回答1:
Ive got this working without using longTouch
and instead just using the panResponder
(same effect as the longTouch
though), take a look:
import React, { Component } from 'react';
import {
View,
PanResponder
} from 'react-native';
const LONGPRESS_TIMER = 300;
class DraggableComponent extends Component {
constructor() {
super();
this.timer = null;
this.state = {
canMove: false
}
this._panResponder = this.setUpPanResponder();
}
setUpPanResponder() {
const self = this;
return PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderGrant: (evt, gestureState) => {
self.timer = setTimeout(() => {
self.setState({canMove: true});
}, LONGPRESS_TIMER);
},
onPanResponderMove: (evt, gestureState) => {
if(this.state.canMove) {
console.log('moving', gestureState);
// code to move view here
}
},
onPanResponderTerminationRequest: (evt, gestureState) => true,
onPanResponderRelease: (evt, gestureState) => {
clearTimeout(self.timer);
self.setState({canMove: false});
}
});
}
render() {
return <View
style={{
width: 100,
height: 100,
backgroundColor: this.state.canMove ? 'green' : 'blue'}}
{...this._panResponder.panHandlers} />
}
}
You can adjust the time it takes to trigger the "canMove" state by changing the LONGPRESS_TIMER
const, Hope it helps!
来源:https://stackoverflow.com/questions/38766763/how-to-emit-a-touch-event-in-react-native