React Native:获取元素的位置 [英] React Native: Getting the position of an element
问题描述
我正在构建一个 Image
组件,其中flexbox位于屏幕中央,效果非常好。现在我想要第二个 Image
组件直接显示在第一个组件的顶部。第二个图像使用绝对定位。目前我只是猜测像素,以便它适合,但当然这不准确,而且可维护性太大。
I am styling an Image
component with flexbox to be in the center of the screen which works pretty well. Now I want a second Image
component to be displayed directly on the top of the first one. The second image is using absolute positioning. Currently I'm just guessing pixels so that it fits, but of course this is not accurate and way too much maintainability effort.
我几乎都在寻找React Native相当于jQuery的 .offset()
。有没有这样的事情,如果没有最好的方法来实现这个目标?
I am pretty much looking for the React Native equivalent of jQuery's .offset()
. Is there such a thing and if there isn't what's the best way to achieve this?
推荐答案
React Native提供了一个 .measure(...)
方法接受回调并使用组件的偏移量和宽度/高度调用它:
React Native provides a .measure(...)
method which takes a callback and calls it with the offsets and width/height of a component:
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)
})
示例...
以下计算自定义组件渲染后的布局:
Example...
The following calculates the layout of a custom component after it is rendered:
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)
})
}
}
< hr>
错误备注
-
请注意,有时组件无法完成渲染调用
componentDidMount()
。如果你从measure(...)
得到零,那么将它包装在setTimeout
中应该解决问题,即:
Bug notes
Note that sometimes the component does not finish rendering before
componentDidMount()
is called. If you are getting zeros as a result frommeasure(...)
, then wrapping it in asetTimeout
should solve the problem, i.e.:setTimeout( myComponent.measure(...), 0 )
这篇关于React Native:获取元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!