微信小程序 组件中createSelectorQuery().select()结果为null

解决方法:

1、在组件在视图层布局完成后执行,即要在ready函数中操作

lifetimes:{
    
    
	ready() {
    
    
		//.....
	},
},

2、如果查询节点为自定义组件内容,则要使用 in() 方法

例如查找的节点为当前组件内容:wx.createSelectorQuery().in(this).select('#the-id')

下面是官方对 in() 方法的说明

SelectorQuery SelectorQuery.in(Component component)

功能描述
将选择器的选取范围更改为自定义组件 component 内。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。

参数
Component component
自定义组件实例

示例代码

Component({
    
    
	queryMultipleNodes (){
    
    
		const query = wx.createSelectorQuery().in(this)
		query.select('#the-id').boundingClientRect(function(res){
    
    
			res.top // 这个组件内 #the-id 节点的上边界坐标
		}).exec()
	}
})

猜你喜欢

转载自blog.csdn.net/weixin_44646763/article/details/126402880