React組件寫法

一、傻瓜組件也叫展示組件

負責根據props顯示頁面信息

聰明組件也叫容器組件

負責數據的獲取、處理

優勢:

分離工作組件和展示組件,解耦

提高組件的重用行

提高組件的可用性和代碼閱讀

便於測試與後續的維護

二、深入理解函數組件

函數式組件是一種無狀態組件,爲了創建純展示組件,這種組件只根據傳入的props來展示,不涉及到要state狀態的操作

組件不會被實例化,整體渲染性能得到提升

組件不能訪問this對象

組件無法訪問生命週期裏的方法

無狀態只能訪問輸入的props。同樣的props會得到同樣的渲染結果,不會有副作用

大部分React代碼中,大多數組件被寫成無狀態的組件,通過簡單組合可以構建成其他的組件等,通過多個簡單然後合併成一個大應用的設計模式被提倡

import React from 'react'
//新建一個組件頁面把組件暴露出去的寫法
export default function Fun(){
    return(
        <div>
        函數組件
        </div>
    )
}
//這種寫法是在頁面內部創建的組件不給外部使用,只供內部頁面調用
function Fun(){
    return(
        <div>
        函數組件
        </div>
    )
}

三、class組件的寫法

在裏面可以寫入狀態、生命週期、構造函數

import React,{Component} from 'react'
export default class Fun extends Component{
    return(
        <div>
        class組件
        </div>
    )
}

高階組件--命名with開頭

高階組件屬性的添加

編寫生命週期

將以上兩個高階組件進行鏈式調用

實現高階組件裝飾器的寫法

高階組件鏈式調用的寫法看起來比較麻煩也比較難理解

ES7出現了裝飾器的語法專門拿來處理這種問題

安裝支持裝飾器語法的babel編譯插件

yarn add --save-dev @babel/plugin-proposal-decorators

更改配置文件代碼

 

組件通信之上下文(context)

上下文context有兩個角色

Provider數據提供

Consumer數據讀取

使用context可以避免通過中間元素傳遞props導致元素的丟失,

context的設計目的是爲了共享對於一個組件樹而言是全局的數據

不使用context的情況下的代碼

import React,{Component} from 'React';
//創建一個傳遞的數據源
let store={
    name:'年後',
    from:'hunter'
}
class Info extends Component{
    render(){
        return (
            <div>
                <p>姓名:{this.props.name}</p>
                <p>出處:{this.props.from}</p>
            </div>
        )
    }
}
function TooBar(props){
    return(
        <div>
            <Info {...props}></Info>
        </div>
    )
}
export default class Composition extends Component {
    render() {
        return (
            <div>
                <TooBar name={store.name} from={store.from}></TooBar>
            </div>
        )
    }
}
使用context修正後的代碼
import React,{Component} from 'React';
//創建上下文
const XdContext =React.createContext();
const {Provider,Consumer}=XdContext
//創建一個傳遞的數據源
let store={
    name:'年後',
    from:'hunter'
}
class Info extends Component{
    render(){
        return (
            <Consumer>
            {
            store=>{
            return(
            <div>
                <p>姓名:{store.name}</p>
                <p>出處:{store.from}</p>
            </div>
        )
     }
}
    </Consumer>
)
}
}
function TooBar(){
    return(
        <div>
            <Info></Info>
        </div>
    )
}
export default class Composition extends Component {
    render() {
        return (
            <div>
                <Provider value={store}>
                    <TooBar></TooBar>
                </Provider>
            </div>
        )
    }
}

 

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