React native get the coordinates of my touch event

How do I get the coordinates of my touch event. So I click anywhere on the display, and I can find the location of X, Y where this happened.

+5
source share
2 answers

You will need to wrap an object of the TouchableOpacity view with one of the other Touchable components. With TouchableOpacity, you have onPress support that runs a press event. At this press event, you get access to the x, y coordinates of the press.

the pseudo code would look like this:

render() { .... <TouchableOpacity onPress={(evt) => this.handlePress(evt) } .... > <View></View> </TouchableOpacity> } handlePress(evt){ console.log(`x coord = ${evt.nativeEvent.locationX}`); } 
+14
source

If you need more flexibility than what is offered with a button, such as TouchableOpacity (for example, if you need gesture movement events), you need to use a gesture recognition system . This allows components to subscribe to touch events.

I included implementation examples for all gesture response event handlers, but commented on most of them in my view to simply provide the basic functions: subscribing to all touch and move events. I demonstrate arrow syntax for boolean functions and use the old-fashioned bind() syntax to call my custom function onTouchEvent(name, ev) .

 import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; export class Battlefield extends Component { constructor(props) { super(props); } // The event 'ev' is of type 'GestureResponderEvent'. Documentation for ev.nativeEvent: // https://facebook.imtqy.com/react-native/docs/gesture-responder-system.html onTouchEvent(name, ev) { console.log( `[${name}] ` + `root_x: ${ev.nativeEvent.pageX}, root_y: ${ev.nativeEvent.pageY} ` + `target_x: ${ev.nativeEvent.locationX}, target_y: ${ev.nativeEvent.locationY} ` + `target: ${ev.nativeEvent.target}` ); } render() { return ( <View style={styles.container} onStartShouldSetResponder={(ev) => true} // onMoveShouldSetResponder={(ev) => false} onResponderGrant={this.onTouchEvent.bind(this, "onResponderGrant")} // onResponderReject={this.onTouchEvent.bind(this, "onResponderReject")} onResponderMove={this.onTouchEvent.bind(this, "onResponderMove")} // onResponderRelease={this.onTouchEvent.bind(this, "onResponderRelease")} // onResponderTerminationRequest={(ev) => true} // onResponderTerminate={this.onTouchEvent.bind(this, "onResponderTerminate")} > <Text>Click me</Text> </View> ); } } const styles = StyleSheet.create({ container: { position: 'relative', height: "100%", width: "100%", backgroundColor: 'orange' } }); 

If functionality is still not enough for you (for example, if you need information with a few touches), refer to PanResponder .

+1
source

Source: https://habr.com/ru/post/1247932/


All Articles