簡體   English   中英

如何在 React Native 中獲取組件在屏幕上的位置?

[英]How to get the position of a component on screen in react native?

我正在開發一個 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>
    );
}

編輯:嘗試此解決方案( 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;} } />
    );
}

謝謝你的幫助!

反應本機

您可以使用.measure()

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

確定給定視圖在屏幕上的位置、寬度和高度,並通過異步回調返回值。 如果成功,將使用以下參數調用回調: xywidthheightpageXpageY

文檔: 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;

結果是包含整個元素的最小矩形,具有只讀的左、上、右、下、x、y、寬度和高度屬性,以像素為單位描述整個邊框框。 寬度和高度以外的屬性相對於視口的左上角。

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

對於在 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)}
    />
  );
};

另一種選擇是使用onLayout 例子

const [viewHeight, setViewHeight] = React.useState(0);
return (
  <View
    onLayout={e => {
      e.persist();
      setViewHeight(e && e.nativeEvent ? e.nativeEvent.layout.height : 0);
    }}
  />
);

一個更深入的例子

LayoutEvent文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM