在React中使用Context在多個嵌套組件內共享數據

Context特性

若組件多層包裹 且外層屬性或方法要傳遞給內層的組件 則傳遞會變得比較麻煩

比如:

import React from 'react';
 
export default class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mycolor:"red"
        }
    }

    render() { 
        return <div>
            <h1>I'm Parent</h1>
            <Son mycolor={this.state.mycolor}></Son>
        </div>
    }
}

class Son extends React.Component {

    render() { 
        return <div>
            <h3>I'm Son</h3>
            <Grandson mycolor={this.props.mycolor}></Grandson>
        </div>
    }
}

class Grandson extends React.Component {

    render() { 
        return <div>
            <h5 style={{color:this.props.mycolor}}>I'm Grandson</h5>
        </div>
    }
}

此時 可以使用Context特性
在父組件上直接共享一個Context對象 然後內層的組件無需逐層傳遞數據了 想要使用 直接從Context獲取即可

在想要共享屬性或方法的父組件裏提供一個getChildContext()方法(方法名不能改變)
在裏面返回一個對象 該對象即爲要共享給所有子孫組件的數據
然後使用childContextTypes屬性進行屬性校驗
在要使用數據的子組件裏使用contextTypes屬性進行屬性校驗 然後用this.context.屬性名獲取屬性即可

像這樣:

import React from 'react';
import ReactPropTypes from 'prop-types' // 屬性校驗包

export default class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mycolor:"red"
        }
    }

    // 在父組件中定義一個function 固定名稱getChildContext 且內部必須返回一個對象
    // 該對象即爲要共享給所有子孫組件的數據
    getChildContext()
    {
        return {
            mycolor:this.state.mycolor
        }
    }

    // 屬性校驗 規定傳給子孫組件的數據類型
    static childContextTypes={
        mycolor:ReactPropTypes.string
    }

    render() { 
        return <div>
            <h1>I'm Parent</h1>
            <Son></Son>
        </div>
    }
}

class Son extends React.Component {

    render() { 
        return <div>
            <h3>I'm Son</h3>
            <Grandson></Grandson>
        </div>
    }
}

class Grandson extends React.Component {

    // 屬性校驗 校驗從父組件傳來的數據類型
    static contextTypes={
        mycolor:ReactPropTypes.string // 若子組件要使用父組件通過Context共享的數據 那麼在使用前一定要進行數據校驗
    }

    render() { 
        return <div>
            <h5 style={{color:this.context.mycolor}}>I'm Grandson</h5>
        </div>
    }
}

當然 Context使用的前提是必須爲父子關係組件 若是平級的組件 則無此特性


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