1.什么是HOC?
所謂高階組件其實就是高階函數,React 和 Vue 都證明了一件事兒:一個函數就是一個組件。所以組件是函數這個命題成立了,那高階組件很自然的就是高階函數,即一個返回函數的函數// 防抖函數 function debounce (func, delay, context, event) { clearTimeout(func.timer) func.timer = setTimeout(function () { func.call(context, event) }, delay) } // 導出新組件 export default { props: {}, name: 'ButtonHoc', data () { return {} }, mounted () { console.log('HOC succeed') }, methods: { handleClickLink (event) { let that = this console.log('debounce') // that.$listeners.click為綁定在新組件上的click函數 debounce(that.$listeners.click, 300, that, event) } }, render (h) { const slots = Object.keys(this.$slots) .reduce((arr, key) => arr.concat(this.$slots[key]), []) .map(vnode => { vnode.context = this._self return vnode }) return h('Button', { on: { click: this.handleClickLink //新組件綁定click事件 }, props: this.$props, // 透傳 scopedSlots scopedSlots: this.$scopedSlots, attrs: this.$attrs }, slots) } }
總結:HOC的特點在於它的包裹性,上列源碼我們做了這些操作,來實現包裹iview的Button組件,劫持click事件,(1)創建debounce防抖函數,導出新組件,render渲染出iview button,button綁定debounce后的click方法。