背景???
開發(fā)時(shí)遇到需要在自定義組件內(nèi)獲取元素的位置的需求,對(duì)于小程序,需要采用到wx.createSelectorQuery()這個(gè)API。但使用Taro這個(gè)框架的話會(huì)有些不同??。
2. 代碼對(duì)比
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. 結(jié)論
Taro中,在自定義組件內(nèi),需要通過this.$scope指向該組件,準(zhǔn)確地說這是編譯為小程序后的組件實(shí)例,而this指向的是編譯前的類react實(shí)例;而小程序this就是本身的組件實(shí)例。
所以SelectorQuery.in(Component component)這個(gè)API在小程序中in(this)就行,Taro中in(this.$scope);
??題外話
- 若為給節(jié)點(diǎn)加上
id屬性,Taro的ref會(huì)給綁定的這個(gè)節(jié)點(diǎn)一個(gè)隨機(jī)字串的id屬性,并添加到ref._selector屬性上,即上面的寫法。 -
query獲取的參數(shù)單位是px,不是rpx。