[英]Find the starting position of the <Text> component in the screen in react native
我有一個圖像背景,我想在它上面寫一些可以在屏幕上任意位置拖動的文本,現在我正在使用“react-native-draggable”組件來完成這項工作。
我的目標是在釋放拖動后找到文本的起始 position(XY 坐標)。 例如:文本是“Hello world”,如果我將它一直向上拖動並完全向左,那么我需要知道 XY = 0、0 的值,如果我水平拖動該文本而不改變 Y,那么 X,Y =說 100,0
我讀過 onLayout 可以做,但我剛開始玩 react native 時無法讓它工作。
這是我的代碼
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>
</>
);
}
}
有人可以提出更好的方法來實現這一目標。 任何幫助深表感謝。
你必須使用 React native 的 PanResponder API。 使用以下鏈接了解更多信息。
是的,你的方法是對的。 您可以使用Text
組件中的onLayout
獲取布局更改,
首先,您必須將onLayout
傳遞給Text
<Text onLayout={this.onLayout}>Hi this is an example</Text>
那么你可以使用
onLayout = (event) => {
const { x, y, height, width } = event.nativeEvent.layout;
console.log(x, y);
}
希望這對您有所幫助。 隨意懷疑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.