0

我想在该元素的 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组件添加到屏幕时,它似乎为所有组件报告了相同的pageY值,就好像它们ref都共享一样或类似的东西。(老实说,我不确定发生了什么,但我确信它们都报告了相同的pageY值,即使它们都明显处于不同的垂直偏移量。)

我正在考虑更改textInput.measureevt.target.measure,但evt.target似乎是元素 ID 而不是实际元素。我在 SO 上阅读了一些关于使用ReactNativeComponentTree从元素 ID 获取实际元素的内容,但我似乎无法正确地要求/导入它。

在这一点上,我被困住了,并且正在寻找任何关于如何在TextInput元素被关注时正确获取元素的垂直偏移的建议,即使TextInput给定屏幕上有多个元素也是如此。谢谢你。


编辑:Max,根据您的评论,我修改了我的功能组件如下:

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事件会针对TextInputCustom屏幕上的第一个组件触发,但其他组件都不会触发。有什么想法吗?谢谢你。

4

0 回答 0