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)
| 归档时间: |
|
| 查看次数: |
8290 次 |
| 最近记录: |