React初探(三)

認(rèn)識props

1.props是父組件傳遞給子組件的參數(shù)
2.props是只讀性的
3.props可以通過父組件傳遞給子組件自身的state的更新函數(shù),然后子組件調(diào)用該更新函數(shù)實現(xiàn)子組件更新父組件數(shù)據(jù)
4.也可以實現(xiàn)一個類似vue中的事件系統(tǒng),子組件調(diào)用emit發(fā)出事件并攜帶參數(shù),父組件監(jiān)聽改事件,接受參數(shù)與完成state更新操作。

簡易事件系統(tǒng)代碼:
// eventProxy.js

const eventProxy = {
  onObj: {},
  oneObj: {},
  on: function (key, fn) {
    if (this.onObj[key] === undefined) {
      this.onObj[key] = [];
    }

    this.onObj[key].push(fn);
  },
  once: function (key, fn) {
    if (this.oneObj[key] === undefined) {
      this.oneObj[key] = [];
    }

    this.oneObj[key].push(fn);
  },
  off: function (key) {
    this.onObj[key] = [];
    this.oneObj[key] = [];
  },
  emit: function () {
    let key, args;
    if (arguments.length === 0) {
      return false;
    }
    key = arguments[0];
    args = [].concat(Array.prototype.slice.call(arguments, 1));

    if (this.onObj[key] !== undefined &&
      this.onObj[key].length > 0) {
      for (let i in this.onObj[key]) {
        this.onObj[key][i].apply(null, args);
      }
    }
    if (this.oneObj[key] !== undefined &&
      this.oneObj[key].length > 0) {
      for (let i in this.oneObj[key]) {
        this.oneObj[key][i].apply(null, args);
        this.oneObj[key][i] = undefined;
      }
      this.oneObj[key] = [];
    }
  }
};

export default eventProxy;
使用方法:
import eventProxy from './eventProxy.js'
eventProxy.emit('change','參數(shù)');
eventProxy.on('change', (params) => { 
// 執(zhí)行邏輯
  console.log(params)
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容