我想在onFocus事件中获取该元素的React Native TextInput的垂直偏移量。我创建的TextInputCustom
组件中有以下代码:
let textInput;
<TextInput
onFocus={(evt) => {
textInput.measure((x, y, width, height, pageX, pageY) => {
console.log('textInput.measure', x, y, width, height, pageX, pageY);
});
}}
ref={(ref) => textInput = ref}
/>
此“有效”是因为我可以看到pageY
的值,但是问题是,当我在屏幕上添加多个TextInputCustom
组件时,似乎报告了相同的{{ 1}}的价值,就好像pageY
被所有人共享一样。 (老实说,我不确定发生了什么,但是我确定他们都报告了相同的ref
值,即使它们显然在垂直偏移上也不同。)
我当时正在考虑将pageY
更改为textInput.measure
,但是evt.target.measure
似乎是元素ID,而不是实际元素。我在SO上阅读了一些有关使用evt.target
从元素ID中获取实际元素的内容,但是我似乎无法正确地要求/导入它。
在这一点上,我陷入了困境,并且寻求关于如何正确获取ReactNativeComponentTree
元素在垂直方向上偏移的任何建议,即使一个元素上有多个TextInput
元素也是如此给定的屏幕。谢谢。
编辑:根据您的评论,我最多修改了我的功能组件,如下所示:
TextInput
我注意到屏幕上的第一个const TextInputCustom = (props) => {
const textInputElem = useRef(null);
<TextInput
onFocus={(evt) => {
textInputElem.current.measure((x, y, width, height, pageX, pageY) => {
console.log('textInput.measure', x, y, width, height, pageX, pageY);
});
}}
ref={textInputElem}
/>
};
组件触发了onFocus
事件,其他事件均未触发。有什么想法吗?谢谢。