如何在屏幕上获取组件的位置以反应原生?

Ale*_*ini 5 javascript react-native

我正在开发一个本机应用程序,我想在屏幕上处理触摸.

一个用例是当用户在屏幕上"按下"时,我希望能够获得屏幕上特定组件的位置(x,y)以知道它是否与触摸的(x,y)匹配.

我已经搜索了堆栈溢出,但没有一个给定的解决方案有效...

在我的根组件中:

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

render() {
    return (
        <View><MyComponent ref={(r) => this._myComponent = r;} /></View>
    );
}
Run Code Online (Sandbox Code Playgroud)

编辑: 尝试此解决方案后(React Native:获取元素的位置)我使其工作如下:

在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;} } />
    );
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Sim*_*one 5

反应本机

您可以使用.measure()

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

确定给定视图在屏幕上的位置、宽度和高度,并通过异步回调返回值。如果成功,将使用以下参数调用回调:x, y, width, height, pageX, pageY

文档:https : //facebook.github.io/react-native/docs/direct-manipulation.html#other-native-methods


Web API(无 React Native)

如果您正在使用 DOM 节点,则可以使用Element.getBoundingClientRect()

let domRect = this._myComponent.getBoundingClientRect();
let { x, y } = domRect;
Run Code Online (Sandbox Code Playgroud)

结果是包含整个元素的最小矩形,具有只读的左、上、右、下、x、y、宽度和高度属性,以像素为单位描述整个边框框。宽度和高度以外的属性相对于视口的左上角。

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

  • 是的,它确实!在阅读了 react native doc 中的两行之后,我得出了这个结论:调用:this._myComponent.measure() 和 this._myComponent._component.measure() 之间的区别在于,在这种情况下 MyComponent 呈现一个“Animated.View”而不是视图,并且可以在任何视图上调用测量函数,但是如果您想在其他东西上调用它(例如,不是“本机视图”),您可以通过引用此“_component”属性。 (2认同)

Kev*_*ams 5

对于在 React Native 中使用 useRef 的功能组件的示例:

const BoardSquare = props => {
  const squareRef = useRef(null);

  console.log('squareRef', squareRef);

  const doMeasure = square => {
    squareRef.current.measure((width, height, px, py, fx, fy) => {
      const location = {
        fx: fx,
        fy: fy,
        px: px,
        py: py,
        width: width,
        height: height,
      };
      console.log('location', location);
      square.x = fx;
      square.y = fy;
      square.xMax = fx + px;
      square.yMax = fy + py;
    });
  };

  return (
    <Square
      {...props}
      ref={squareRef}
      filled={props.square.filled}
      onLayout={() => doMeasure(props.square)}
    />
  );
};
Run Code Online (Sandbox Code Playgroud)