【问题标题】:Find the starting position of the <Text> component in the screen in react nativereact native中找到<Text>组件在屏幕中的起始位置
【发布时间】:2020-04-30 14:35:58
【问题描述】:

我有一个图像背景,我想在它上面写一些可在屏幕上任意位置拖动的文本,现在我正在使用“react-native-draggable”组件来完成这项工作。

我的目标是在释放拖动后找到文本的起始位置(X Y 坐标)。 例如:文本是“Hello world”,如果我一直向上拖动并完全向左,那么我需要知道 X Y = 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>


      </>
    );
  }
}

有人可以提出更好的方法来实现这一点。非常感谢任何帮助。

【问题讨论】:

    标签: javascript reactjs react-native react-hooks


    【解决方案1】:

    您必须使用 React 本机的 PanResponder API。 使用以下链接了解更多信息。

    https://reactnative.dev/docs/panresponder

    【讨论】:

    • 此类通用指针可以写为评论,但不能作为问题的解决方案,因为您的帖子实际上并没有回答问题。这就像有人问你商场在哪里,你只是指着某个方向说“那边”。方向类似于谷歌地图给出的方向。答案应该是这样的。
    【解决方案2】:

    是的,您的方法是正确的。您可以使用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);
    }
    

    希望这对您有所帮助。如有疑问,请随意。

    【讨论】:

    • 在布局上给出与该文本组件相关的 xy 位置。例如,如果我触摸字母“h”,则 x = 0,但如果触摸最后一个字母“e”,则 x= 说 100。但我想知道与图像背景相关的文本的起始位置
    • @MadhuBabu 实际上给出了相关的位置。不像if I touch at the letter "h" then x = 0 but if touch at the last letter "e" that gives x=100
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    相关资源
    最近更新 更多