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)
谢谢你的帮助!
您可以使用.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
如果您正在使用 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 中使用 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)
| 归档时间: |
|
| 查看次数: |
5008 次 |
| 最近记录: |