如何找到功能性反应本机组件中的组件位置

Tea*_*amo 4 position react-native react-hooks

我试图在渲染后动态查找组件的位置。我尝试使用 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;
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以尝试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;
Run Code Online (Sandbox Code Playgroud)

  • 如果我尝试在我的应用程序中使用上面的组件,它会引发错误... ref 对象上也不存在测量方法。 (3认同)