我正在开发一个本机应用程序,我想在屏幕上处理触摸.
一个用例是当用户在屏幕上“按下”时,我希望能够获得屏幕上特定组件的位置(x,y)以知道它是否与触摸的(x,y)匹配.
在我的根组件中:
_onPress = () => {
// How can I get the position of my component ?
this._myComponent.xxx();
};
render() {
return (
编辑:
在尝试此解决方案(React Native: Getting the position of an element)后,我使其工作如下:
在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 (
谢谢你的帮助!@H_404_27@
你可以使用.measure():
this._myComponent._component.measure((width,fy) => {
// do positioning checks here
}
Determines the location on screen,width,and height of the given view and returns the values via an async callback. If successful,the callback will be called with the following arguments:
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;
The result is the smallest rectangle which contains the entire element,with read-only left,top,right,bottom,x,y,and height properties describing the overall border-Box in pixels. Properties other than width and height are relative to the top-left of the viewport.
文件:https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect@H_404_27@