[英]How to get current touch coordinates of PanResponder relative to parent view?
使用React-Native,我正在嘗試捕獲列表視圖項上的滑動事件。 一切都運作良好,但相對於列表視圖項,我很難獲取觸摸手勢的當前坐標。
在我的_handlePanResponderMove
,我使用以下代碼段:
let relativeY = event.nativeEvent.locationY;
不幸的是,我得到的Y坐標是相對於滑動發生的“子視圖”,而不是相對於列表視圖項(正如我所料,因為我將PanResponder附加到列表視圖項)
如何獲得相對於列表視圖父級的手勢Y坐標?
將子視圖設置為pointerEvents="none"
如下所示:
<View pointerEvents="none">
...
</View>
這樣,您在event.nativeEvent.locationY
上收到的事件將根本不考慮子視圖坐標,這將完全符合您的要求。
嘗試為孩子添加一個ref,然后測量它的相對距離。 此代碼表示具有widget
(子組件)的包裝器。 這個對我有用! 請注意, this.refs.self.measure
是在setTimeout之后觸發的,沒有它就無法工作。 可能是一個測量錯誤或者在瞬間之后沒有更新引用。
import React, { Component } from 'react'
import TimerMixin from 'react-timer-mixin'
import {
StyleSheet,
View,
TouchableHighlight,
Text,
Alert,
PanResponder,
Animated,
Dimensions } from 'react-native'
import BulbWidget from './bulb-widget'
const COLUMNS = 3
export default class Widget extends Component {
constructor (props) {
super()
this.state = {
pan: new Animated.ValueXY(),
touches: 1
}
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([null, {
dx: this.state.pan.x,
dy: this.state.pan.y
}]),
onPanResponderRelease: (e, gesture) => {
this.state.pan.flattenOffset()
this._setPosition(gesture)
Animated.spring(
this.state.pan,
{toValue: {x: 0, y: 0}}
).start()
},
onPanResponderGrant: (e, gestureState) => {
this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value})
this.state.pan.setValue({x: 0, y: 0})
this._onPressWidget()
}
})
}
render () {
let styleWidget = {}
this.props.type === 'L' ? styleWidget = styles.widgetL : styleWidget = styles.widget
return (
<View ref='self' style={this.state.placed}>
<Animated.View {...this.panResponder.panHandlers}
style={[this.state.pan.getLayout(), styleWidget]} >
<BulbWidget ref='child'/>
</Animated.View>
</View>
)
}
componentDidMount () {
// Print component dimensions to console
setTimeout(() => {
this.refs.self.measure((fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
this.offset = { fx, fy, width, height }
})
}, 0)
}
_onPressWidget () {
this.refs.child.onPressAction()
this.setState({touches: this.state.touches + 1})
TimerMixin.setTimeout(() => {
this.setState({ touches: 1 })
console.log('Reset')
}, 1000)
if (this.state.touches === 2) {
this.setState({touches: 1})
}
}
_setPosition (gesture) {
const dx = gesture.moveX - gesture.x0
const dy = gesture.moveY - gesture.y0
const { width, height } = this.offset
const x = Math.abs(this.offset.fx + dx)
const y = Math.abs(this.offset.fy + dy)
const idTo = (Math.floor(x / width) + Math.floor(y / height) * COLUMNS)
this.props.setPosition(gesture, this.props.idx, idTo)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.