函數式組件在React
社區很流行使用,那么在vue里面我們要怎么用呢
下面會涉及到的知識點: 高階函數、狀態、實例、vue組件
什么是函數式組件
我們可以把函數式組件想像成組件里的一個函數,入參是渲染上下文(render context),返回值是渲染好的HTML
對於函數式組件,可以這樣定義:
- Stateless(無狀態):組件自身是沒有狀態的
- Instanceless(無實例):組件自身沒有實例,也就是沒有this
由於函數式組件擁有的這兩個特性,我們就可以把它用作高階組件(High order components),所謂高階,就是可以生成其它組件的組件。就像日本的高精度的母機。
下面示例的完整Demo
那創造一個函數式組件吧
functional: true
加上render function
,就是一個最簡單的函數式組件啦,show your the code, 下面就創建一個名為FunctionButton.js
的函數式組件
export default { name: 'functional-button', functional: true, render(createElement, context) { return createElement('button', 'click me') } }
就像上文所講的,函數式組件沒有this,參數就是靠context
來傳遞的了,下面我們看下context
有哪些屬性呢
Render context
props
children
slots
(a slots object)parent
listeners
injections
data
其中上面的data
包含了其他屬性的引用,nibility。 在下面的范例中會有具體使用
現在創建一個App.vue
來引入上面的函數式組件
<template>
<FunctionalButton>
click me
</FunctionButton>
</template>
上面的click me
就是FunctionButton.js
的childern
屬性了,我們可以把組件改造下,由App.vue
來定義組件的button按鈕
export default { name: 'funtional-button', functional: true, render(createElement, { children }) { return createElement('button', children) } }
看,上面用了ES6參數的解構,用{children}
來代替context
事件定義
函數式組件沒有實例,事件只能由父組件傳遞。下面我們在App.vue
上定義一個最簡單的click
事件
<template>
<FunctionalButton @click="log">
Click me
</FunctionalButton>
</template>
對應的FunctionalButton.js
export default { functional: true, render(createElement, { props, listeners, children }) { return createElement( 'button', { attrs: props, on: { click: listeners.click } }, children ); } };
對了,createElement
里事件屬性就是on
了。具體可以看vue
的官方文檔
簡單的寫法
尤大設計的Api還是很人性的,上面涉及到的props
、listeners
那么多要傳遞的,是不是很麻煩,所以尤大統一把這個屬性集成在data
里了,我們可以再改寫下
export default { functional: true, render(createElement, { data, children }) { return createElement( 'button', data, children ); } };
恩,是不是感覺世界清爽了不少
這就是一個完整的高階組件了,下面小小的展示一下高階的魅力。
createElement('button', data, ['hello', ...children])
恩,很簡單的就DIY了一個自帶hello
的button按鈕
The end
上面就是關於函數式組件的基礎定義和基本使用了,希望對你們的學習有幫助。
demo效果圖: