【发布时间】:2021-06-01 13:18:22
【问题描述】:
当文本光标聚焦在 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
没有办法在功能组件中获取 ref 的位置吗?
【问题讨论】:
标签: scrollview react-functional-component use-ref react-native-textinput