How to get the position of the component on the screen in the native response?

I am working on an adaptive native application and I want to handle the strokes on the screen.

One use case is when the user “clicks” on the screen, I want to get the position (x, y) of a particular component on the screen to find out if it matches (x, y) the touch.

I was already looking for stack overflow, but none of these solutions worked ...

In my root component:

_onPress = () => {
    // How can I get the position of my component ?
    this._myComponent.xxx();
};

render() {
    return (
        <View><MyComponent ref={(r) => this._myComponent = r;} /></View>
    );
}

EDIT: Having tried this solution ( React Native: Getting the position of an element ), I did it like this:

In MyComponent.js:

getPosition () => {
    this._ref._component.measure((width, height, px, py, fx, fy) => {
        const location = {
            fx: fx,
            fy: fy,
            px: px,
            py: py,
            width: width,
            height: height
        }
        console.log(location)
    });
};

render() {
    return (
        <View ref={(r) => { this._ref = r;} } />
    );
}

Thank you for your help!

+4
source share
1 answer

React native

You can use .measure():

this._myComponent._component.measure((width, height, px, py, fx, fy) => {
  // do positioning checks here
}

, . : x, y, width, height, pageX, pageY.

: https://facebook.imtqy.com/react-native/docs/direct-manipulation.html#other-native-methods


-API ( )

DOM node, Element.getBoundingClientRect():

let domRect = this._myComponent.getBoundingClientRect();
let { x, y } = domRect;

, , , , , , , , , , , . , , .

: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

+2

Source: https://habr.com/ru/post/1689776/


All Articles