【发布时间】: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