如何在 React Native 中找到组件的 x,y 位置

Jon*_*ley 4 react-native

如何找出元素在屏幕上的 x、y 位置,我使用的是 React Native v0.14。我尝试了以下操作,但它说度量不是函数。

componentDidMount() {
    setTimeout(this.measurePosition);
  },
measurePosition() {
    this.refs.q.measure((a, b, width, height, px,py ) => console.log(width))
},
Run Code Online (Sandbox Code Playgroud)

Nis*_*kar 6

选项1:

您可以使用 NativeMethodsMixin。确保您已将 mixin 添加到您的课程中

var NativeMethodsMixin = require('NativeMethodsMixin')
...
var MyComponent = React.createClass({
  mixins: [NativeMethodsMixin]
...
componentDidMount: function(){
  this.refs.element.measure((x,y,w,h,pX,pY) => console.log("dets"))
}
Run Code Online (Sandbox Code Playgroud)

选项 2

您可以在视图上使用 onLayout 属性。它可用于大多数组件。

render:function(){
... 
<View onLayout = {this.onLayout} />
...
},
onLayout:function(event){
  console.log(event.nativeEvent.layout)
}
Run Code Online (Sandbox Code Playgroud)

您将获得 x、y、宽度和高度


Dav*_*vet -6

你可以使用类似的东西 1. 使用 (ReactDOM.findDOMNode()) 获取浏览器 DOM 元素 2. 使用元素 getBoundingClientRect() 3. 你有顶部、左侧、底部和右侧坐标

这也可能有用检索 HTML 元素的位置 (X,Y)