一、问题场景
有些场景下,我们需要在小程序自定义组件中获取某些元素的高度,代码如下:
ready: function() {
wx.createSelectorQuery().select('.search-content').boundingClientRect(rect=>{
console.log(rect.height)
}).exec();
}
会发现并不能取到,报错如下:
二、如何解决
const query = wx.createSelectorQuery().in(this)
这一句是最重要的,要用 in(this),this传入的是自定义组件的实例,否则获取到的rect值为null。
代码如下:
ready: function() {
const query = wx.createSelectorQuery().in(this)
query.select('.search-content').boundingClientRect(rect=>{
console.log(rect.height)
}).exec();
}
发现成功取到了rect