React組件化和UI庫引入使用

引入ant-design組件庫

npm install antd --save

yarn add antd --save

一、按需加載

加載全部的antd組件的樣式(對前端性能有隱患)

需要對antd進行配置進行按需加載,需要對create-react-app的默認配置進行自定義

需要更改我們的啓動插件

引入react-app-rewired並修改package.json裏的啓動配置。由於新的[email protected]版本的關係還要安裝customize-cra

 

二、安裝命令yarn add react-app-rewired customize-cra

更改package.json文件

然後在根目錄創建一個config-overrides.js,用於修改默認配置,先不用寫內容

執行安裝babel-plugin-import插件(命令yarn add babel-plugin-import)

修改config-overrides.js文件內容如下

const {override,fixBabelImports}=require('customize-cra');
module.exports=override(
    fixBabelImports('import',{
        libraryName:'antd',
        libraryDirectory:'es',
        style:'css'
    })
)
import Button from 'antd'

 

三、性能優化PurComponent講解

PurComponent是內部定製了shouldComponentUpdate生命週期的Component

它重寫了一個方法來替換shouldComponentUpdate生命週期

平常開發過程設計組件能使用PurComponent都儘量使用

使用特性要記住兩個小原則

確保數據類型是值類型

如果是引用類型,確保地址不變,同時不應當有深層次數據變化

使用PurComponent可以省Reac去shouldComponentUpdate生命週期的代碼,代碼還會簡單很多

 

四、React.memo講解

React.memo是一個高階組件的寫法

React.memo讓函數組件也擁有PurComponent的功能

 

五、React高級使用之組件複合寫法

React官方說任何一個能用組件繼承實現的用組件複合都可以實現,所以可以放心使用

組件複合類似於我們在Vue框架裏的組件插槽

funtion XdDialog(props){
    return(
        <div style={{border:'4px solid red'}}>
            {/*等於Vue中匿名插槽*/}
            {props.children}
            {/*等於Vue中具名插槽*/}
           <div className="ads">
            {props.footer}
            </div>
        </div>
    )
}
function WelcomeXdDialog(){
    const fonfirmBtn=(<button onClick={()=>alert("確定?")}>確定</button>)
    return(
        <XdDialog color="green" footer={fonfirmBtn}>	
            <p>歡迎歡迎</p>
        </XdDialog>
    )
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章