问题描述
当文本光标聚焦在 TextInput 上时,我想获取 x、y 位置。
如何获得引用位置?
这是我的代码
const Code = () => {
const emailInput = useRef();
const scrollViewRef = useRef();
const [email,setEmail] = useState<string>('');
const scrollToEmail = () => {
// I want to scroll the y position of the scroll to the center where the TextInput's cursor is focused.
};
return (
<SafeAreaView style={{ flex: 1}}>
<ScrollView keyboardShouldPersistTaps="handled" ref ={scrollViewRef}>
<KeyboardAvoidingView enabled behavior={'padding'}>
<TextInput
ref={emailInput}
value={email}
returnKeyType="done"
onChangeText={(text) => setEmail(text)}
onFocus = {() => scrollToEmail()} <== function works here!
/>
</KeyboardAvoidingView>
</ScrollView>
</SafeAreaView>
);
};
export default Code;
我试过了
1.
const handler = findNodeHandle(emailInput.current);
console.log(
emailInput.measure(handler,(x,y,width,height) => {
console.log(y);
}),); <== TypeError: emailInput.measure is not a function
const handler = findNodeHandle(emailInput.current);
console.log(emailInput.current.getBoundingClientRect()); <== TypeError: emailInput.current.getBoundingClientRect is not a function
解决方法
您可以在 ScrollView 上使用 onLayout
属性来设置高度、宽度、X 和 Y 值。
如果您想使用 ref
,您必须在 useLayoutEffect
上设置或控制台记录 X 和 Y 值。这是因为你需要等待组件被渲染和“绘制”后才得到信息,否则你只会得到0