与using .measure() as shown in the accepted answer相比,这样做的好处是,您永远不必随意使用 setTimeout 推迟 .measure() 调用,以确保测量结果可用,但缺点是它不是't give you offsets relative to the entire page, only ones relative to the element'的父级 .
08-24 11:15:36.838 3727 27838 I ReactNativeJS: Component width is: 156
08-24 11:15:36.838 3727 27838 I ReactNativeJS: Component height is: 206
08-24 11:15:36.838 3727 27838 I ReactNativeJS: X offset to page: 188
08-24 11:15:36.838 3727 27838 I ReactNativeJS: Y offset to page: 870
5 回答
React Native提供了一个.measure(...)方法,该方法接受回调并使用组件的偏移量和宽度/高度调用它:
示例......
下面计算自定义组件呈现后的布局:
Bug说明
componentDidMount()
之前未完成渲染 . 如果你从measure(...)
得到零,那么将它包装在setTimeout
应该可以解决问题,即:我需要在ListView中找到一个元素的位置,并使用这个类似于
.offset
的片段:这假设我的组件上有
ref='myElement'
.您可以使用onLayout在组件可用的最早时刻获取组件的宽度,高度和相对父级位置:
与using .measure() as shown in the accepted answer相比,这样做的好处是,您永远不必随意使用
setTimeout
推迟.measure()
调用,以确保测量结果可用,但缺点是它不是't give you offsets relative to the entire page, only ones relative to the element'的父级 .我有一个类似的问题,并通过结合上面的答案解决它
现在我可以在日志中看到feedPost元素的位置:
在使用refs计算时,最新版本的React Native似乎已经改变了 .
以这种方式声明引用 .
并以这种方式找到 Value .