你真的瞭解元件化設計嗎?
本週開始動工新專案 , 相比之前的開發過程 , 這次定製了很多規範 , 比如react寫法 (一個檔案內部不允許出現兩個類) , 可重用元件要封裝設計 ,引入ts後 , 變數定義型別不允許出現any , 定期commit , 定期codeReview , and so on .
那麼這麼做的目的是什麼呢? 如果我們不按照種種規範準則 , 不也照樣能實現功能需求嗎 , 對吧 ? 可是呢 , 長遠來看 , 程式碼的可讀性 , 是否冗餘, 耦合度高低 ,後期的可維護性 , 產生bug的概率 等, 都和開發時的規範與否密切相關的, 團隊協作 , 不僅要對自己負責 , 也要對所有小夥伴負責 , 為使用者負責 .
所以 , 這次我就大家耳熟能詳的元件化設計來做一個分享,昨天大佬在codeReview時,對我的元件化寫法是無比的恐懼與無奈啊 , This is not what I imagined !
因為我的元件化顆粒度不夠小 , 而且並沒有以封裝的思想去設計 , 這隻能怪自己平時 Bad coding habit
說一下個人對此的理解吧,當我們要設計一個元件時:
first , 要考慮是它需要什麼樣的入參 , 需要向外暴露哪些介面
second , 還原UI
final , 測試功能
封裝一個Button的demo為例:
MyButton.tsx
import React from 'react'; interface PropsTypes { size?: string;// 按鈕的大小 disable?: boolean;// 是否禁用 onClick?: () => void;// 點選事件 } export default class NyButton extends React.Component<PropsTypes> { private sizeObj: { [key: string]: { smallBtn: string; defaultBtn: string; largeBtn: string; }; } = { smallBtn: className.smallBtn, defaultBtn: className.defaultBtn, largeBtn: className.largeBtn }; onClickBtn() { this.props.onClick(); } render() { return ( <button onClick={this.onClickBtn} disabled={this.props.disable ? this.props.disable : false} className={ (this.sizeObj[this.props.size] || className.defaultBtn) + ' ' + (this.props.disable ? className.unable : '') } > {this.props.children ? this.props.children : 'Button'} </button> ); } }
在component 層 , 我們編寫了一個button , 而在這之前 , 我們在interface處定義了 它的引數 及型別 , ,我們再來看container層對他的引用是怎麼做的
class App extends React.Component<PropsTypes> { render() { return ( <MyButton {...this.props} disable={true} size="largeBtn" onClick={() => { console.log(123); }} > 按鈕 </MyButton> ); } }
在引入時 , 我們可以根據自己的實際需要傳入引數 , 去控制組件 , 比如: 傳入 disable 表示是否禁用 , small , default , large , 選擇用不同大小的樣式 , 寫入點選事件等
比如: size = 'largeBtn'

2019-04-05_150626.png
size = 'defaultBtn'
disable = {true}

2019-04-05_150844.png
size= ' smallBtn '

2019-04-05_150717.png
只是為了掩飾一下效果 , 忽略樣式;
元件化設計 , 是對元件的抽象化,或者說是面向物件的思想 , 關鍵在於考慮其 介面處的定義 , 需要哪些引數 , 暴露什麼介面等 , 這樣設計出來的組價 , 才是具備高價值的 , 無論你用vue , react , 都是同樣的思想 , react 的世界觀裡 , 一切元件化 , 連路由都可以元件化 , 而且元件化顆粒度越小 , 效能越好 ( 但也要有控制範圍的 ) , 如果不是這樣 , 那我們用react vue 等的意義何在 ?