支付寶小程序框架 自定義組件·ref獲取組件實(shí)例

2020-09-18 10:31 更新

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>

自定義組件 ref 定義段

自基礎(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' }
  },
});
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號