W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
從 1.14.0
版本開始,自定義組件支持使用 ref 獲取自定義組件實(shí)例,可以使用 my.canIUse('component2') 做兼容。 并且,需要在 IDE 中的 詳情 > 項(xiàng)目配置 中,勾選 component2。
// /pages/index/index.js
Page({
plus() {
this.counter.plus();
},
// saveRef 方法的參數(shù) ref 為自定義組件實(shí)例,運(yùn)行時(shí)由框架傳遞給 saveRef
saveRef(ref) {
// 存儲自定義組件實(shí)例,方便以后調(diào)用
this.counter = ref;
},
});
<!-- /pages/index/index.axml -->
<my-component ref="saveRef" />
<button onTap="plus">+</button>
說明:
ref
綁定 saveRef
之后,會在組件初始化時(shí)觸發(fā) saveRef
方法。saveRef
方法的參數(shù)ref
為自定義組件實(shí)例,由框架傳遞給saveRef
方法。ref
同樣可以用于父組件獲取子組件的實(shí)例。// /components/index/index.js
Component({
data: {
counter: 0,
},
methods: {
plus() {
this.setData({ counter: this.data.counter + 1 })
},
},
})
<!-- /components/index/index.axml -->
<view>{{counter}}</view>
自基礎(chǔ)庫 1.18.0
開始,自定義組件(component2)支持使用 ref 定義段指定調(diào)用者傳遞ref時(shí)獲取的值。 未使用 ref 定義段時(shí),調(diào)用者傳遞ref獲取的值是自定義組件的 this
(插件的自定義組件將返回 null
)。 使用這個(gè)定義段時(shí),將以這個(gè)定義段的函數(shù)返回值代替。
// 自定義組件內(nèi)部
// /components/index/index.js
Component({
ref() {
return { key: 'value' }
}
<!-- 使用自定義組件時(shí) -->
<!-- /pages/index/index.axml -->
<my-component ref="saveRef" />
// /pages/index/index.js
Page({
// 此時(shí)saveRef 方法的參數(shù) ref 即是 my-component 自定義組件中的 ref 定義段的返回值
saveRef(ref) {
// 存儲自定義組件實(shí)例,方便以后調(diào)用
this.counter = ref; // 等于 { key: 'value' }
},
});
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: