背景🗺️
开发时遇到需要在自定义组件内获取元素的位置的需求,对于小程序,需要采用到wx.createSelectorQuery()这个API。但使用Taro这个框架的话会有些不同🙁。
2. 代码对比
1.小程序
// index.js
onReady(){
const query = wx.createSelectorQuery()
.in(this)
.select('#selectMe')
.boundingClientRect()
.exec(console.log);
}
<!--index.wxml-->
<view id='selectMe'></view>
2.Taro
// index.jsx
componentDidMount(){
+ const query = wx.createSelectorQuery()
.in(this.$scope);
+ .select(this.ref._selector) // .select('.select Me')
.boundingClientRect()
.exec(console.log);
}
render(){
<View
className="select Me"
ref={node => this.ref = node}
></View>
}
3. 结论
Taro中,在自定义组件内,需要通过this.$scope指向该组件,准确地说这是编译为小程序后的组件实例,而this指向的是编译前的类react实例;而小程序this就是本身的组件实例。
所以SelectorQuery.in(Component component)这个API在小程序中in(this)就行,Taro中in(this.$scope);
📃题外话
- 若为给节点加上
id属性,Taro的ref会给绑定的这个节点一个随机字串的id属性,并添加到ref._selector属性上,即上面的写法。 -
query获取的参数单位是px,不是rpx。