【问题标题】:How do I find the component position in a functional react-native component如何在功能性反应原生组件中找到组件位置
【发布时间】:2019-11-15 13:23:21
【问题描述】:

我试图在渲染后动态查找组件的位置。我试图使用 useRef 和 getBoundingClientRect() (见下面的代码)。

我得到的回应是这样的。

myRef.current.getBoundingClientRect 不是函数。 (在 'myRef.current.getBoundingClientRect()' 中,'myRef.current.getBoundingClientRect' 是未定义的)。

任何想法我做错了什么?

import React, { useState, useRef } from "react";
import { View, Button, TextInput } from "react-native";

const MyComponent = () => {
  const [value, onChangeText] = useState("Useless Placeholder");

  const myRef = useRef();

  const showRefPosition = () => {
    console.log("button clicked, set focus and log position");
    // this works and shows that i am using the ref correctly
    myRef.current.focus();

    // however, this does not work and throws the eror
    let componentPosition = myRef.current.getBoundingClientRect();
    console.log(`Component Position ${componentPosition}`);
  };

  return (
    <View>
      <TextInput
        style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
        onChangeText={text => onChangeText(text)}
        value={value}
        ref={myRef}
      />
      <Button title="Click Me" onPress={() => showRefPosition()} />
    </View>
  );
};

export default MyComponent;

【问题讨论】:

    标签: react-native position react-hooks


    【解决方案1】:

    你可以在 react-native 中尝试 measure 方法。

    import React, { useState, useRef } from "react";
    import { View, Button, TextInput } from "react-native";
    
    const MyComponent = () => {
      const [value, onChangeText] = useState("Useless Placeholder");
    
      const myRef = useRef();
    
      const showRefPosition = () => {
        console.log("button clicked, set focus and log position");
        // this works and shows that i am using the ref correctly
        this.ref.measure( (width, height) => {
          console.log('Component width is: ' + width)
          console.log('Component height is: ' + height)
        })
      };
    
      return (
        <View>
          <TextInput
            style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
            onChangeText={text => onChangeText(text)}
            value={value}
            ref={(ref) => { this.ref = ref; }}
          />
          <Button title="Click Me" onPress={() => showRefPosition()} />
        </View>
      );
    };
    
    export default MyComponent;
    

    【讨论】:

    • 谢谢@firats - 为我整理好了:)。看起来我的主要问题是使用 useRef 来设置 ref 而不是 ref={ref => {myNewRef = ref;}}。不知道为什么 useRef 不起作用。
    • 以防万一其他阅读此内容的人与我类似,测量可以采用以下参数 originX、originY、宽度、高度、pageX、pageY。 pageX 和 pageY 会给你你的位置。
    • @TeamBeamo 使用 useRef 应该没问题。问题是 getBoundingClientRect 仅适用于网络。
    • 如果我尝试在我的应用程序中使用它,上面的组件会给我一个错误...... ref 对象上也不存在 measure 方法。
    • 这在函数组件中返回未定义
    猜你喜欢
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多