I have an image background, on it I want to write some text which is draggable any where in the screen, Right now I am using the "react-native-draggable" component to do that job.
My goal is this find the starting position (XY coordinates) of the text once the drag is released. Ex: the text is "Hello world ", if i drag that all the way up and fully left, then I need to know the values of XY = 0, 0, if I drag that text horizontally without Y change then X,Y = say 100,0
I have read onLayout can do but I could not make it work as I just started playing with react native.
Here is My code
import React from 'react';
import { StyleSheet, Text, View, ImageBackground, StatusBar, Button, Dimensions,Image } from 'react-native';
import Draggable from 'react-native-draggable';
export default class App extends React.Component {
constructor(props) {
super(props);
this.maxWidth = Dimensions.get('window').width - 20;
this.maxHeight = Dimensions.get('window').height - 40;
this.state = {};
}
onDragReleaseCustom(value) {
console.log('drag release', value.nativeEvent);
console.log('drag release', value.nativeEvent);
}
onLayout = (e) => {
console.log("working gere");
console.log(e.nativeEvent);
console.log("widht,height",e.nativeEvent.layout.x,e.nativeEvent.layout.y)
}
render() {
return (
<>
<StatusBar hidden />
<View style={styles.container}>
<ImageBackground source={require('./assets/bg1.jpg')} style={styles.backgroundImage}>
</ImageBackground>
</View>
<Draggable
minX = {15}
minY = {15}
maxX = {this.maxWidth}
maxY = {this.maxHeight}
x = {30}
y = {112}
onDragRelease = {this.onLayout()}>
<View >
<Text style={styles.customText}>Hi this is an example </Text>
</View>
</Draggable>
<View style={styles.buttonStyle}>
<Button color="#f00fff" title="Save"></Button>
</View>
</>
);
}
}
Can somebody suggest better ways to achieve this. any help is much appreciated.
You'll have to use PanResponder API of React native. Use the following link to explore more about it.
Yes, your approach is right. You can get the layout changes using onLayout
prop in Text
component,
First you have to pass onLayout
to Text
<Text onLayout={this.onLayout}>Hi this is an example</Text>
then you can get value using
onLayout = (event) => {
const { x, y, height, width } = event.nativeEvent.layout;
console.log(x, y);
}
Hope this helps you. Feel free for doubts.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.