反应本机:获取元素的位置
我正在devise一个带flexbox的Image
组件,它位于屏幕的中心,效果很好。 现在我想要第二个Image
组件直接显示在第一个的顶部。 第二个图像是使用绝对定位。 目前我只是猜测像素,以便它适合,但当然这是不准确的,太多的可维护性努力。
我非常喜欢jQuery的.offset()
的React Native等价物。 有没有这样的事情,如果没有什么是最好的办法来实现这一目标?
React Native提供了一个.measure(...)
方法,它接受一个callback,并用一个组件的偏移量和宽度/高度来调用它:
myComponent.measure( (fx, fy, width, height, px, py) => { console.log('Component width is: ' + width) console.log('Component height is: ' + height) console.log('X offset to frame: ' + fx) console.log('Y offset to frame: ' + fy) console.log('X offset to page: ' + px) console.log('Y offset to page: ' + py) })
例…
以下内容将在渲染后计算自定义组件的布局:
class MyComponent extends React.Component { render() { return <View ref={view => { this.myComponent = view; }} /> } componentDidMount() { // Print component dimensions to console this.myComponent.measure( (fx, fy, width, height, px, py) => { console.log('Component width is: ' + width) console.log('Component height is: ' + height) console.log('X offset to frame: ' + fx) console.log('Y offset to frame: ' + fy) console.log('X offset to page: ' + px) console.log('Y offset to page: ' + py) }) } }
臭虫笔记
-
请注意,有时组件在调用
componentDidMount()
之前不会完成呈现。 如果由于measure(...)
而得到零,那么将其包装在setTimeout
可以解决问题,即:setTimeout( myComponent.measure(...), 0 )
我需要find一个ListView中的一个元素的位置,并使用这个类似.offset
:
const UIManager = require('NativeModules').UIManager; const handle = React.findNodeHandle(this.refs.myElement); UIManager.measureLayoutRelativeToParent( handle, (e) => {console.error(e)}, (x, y, w, h) => { console.log('offset', x, y, w, h); });
这假定我的组件上有一个ref='myElement'
。
在使用refs进行计算时,这似乎已经在最新版本的React Native中发生了变化。
用这种方式声明refs。
<View ref={(image) => { this._image = image }}>
并以这种方式find价值。
_measure = () => { this._image._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) }) }
您可以使用onLayout
获取组件的宽度,高度和框架相对位置。
<View onLayout={event => { const layout = event.nativeEvent.layout; console.log('height:', layout.height); console.log('width:', layout.width); console.log('x:', layout.x); console.log('y:', layout.y); }} >
与使用.measure()
(如接受的答案中所示.measure()
相比,这具有以下优点:您.measure()
在setTimeout
延迟调用.measure()
调用以确保测量结果可用,但缺点是不会给你页面相关的偏移量,只有框架相对的偏移量。
要获取有关任何元素的信息,可以简单地显示检查器。
打开debugging模式(在iOS模拟器上,在Hardware> Shake gesture下):
反应原生debugging模式
它与Web DOM检查器类似,您可以select图层并查看样式属性以及位置。
React Native Inspector