context上下文數(shù)據(jù)傳遞

props的缺點(diǎn)

通常情況下,組件之間的數(shù)據(jù)傳遞可以通過props傳遞,但是props數(shù)據(jù)的傳遞是必須是一一傳遞,比如有三個(gè)組件:A、B、C, 其中B組件是A組件的子組件,C組件是B組件的子組件,如果A組件的數(shù)據(jù)要傳遞給C組件,就需要A->B->C,數(shù)據(jù)的傳遞不能跨級(jí),用起來就比較麻煩

Context的優(yōu)點(diǎn)

組件之間的數(shù)據(jù)傳遞是可以跨級(jí)的,只有起點(diǎn)和終點(diǎn)

使用步驟
  1. 創(chuàng)建context.js,內(nèi)容如下:
import React from 'react'
//創(chuàng)建context對(duì)象
const MyContext=React.createContext();
//Provider:生產(chǎn)商(提供公共數(shù)據(jù))
//Consumer:用戶(用戶使用公共數(shù)據(jù))
const {Provider,Consumer}=MyContext
export {MyContext,Provider,Consumer}
  1. 創(chuàng)建Father.js(A組件)
import React, { useState } from 'react';
import {Provider} from './context';
import Son from './Son'
const Facther = () => {
  // hook state定義數(shù)據(jù)和修改數(shù)據(jù)
   const [username,setUsername]=useState('小明')
   return (
//  value里定義的就是公共數(shù)據(jù)或者方法
       <Provider value={{
           username,setUsername
       }}>
      <Son />
  </Provider>
   );
}

export default Facther;
  1. 創(chuàng)建Son組件(C組件)
import React from 'react';
import {Consumer} from './context'
const Son = () => {
    return (
        <Consumer>
          {/*Comsumer中帶有一個(gè)回調(diào)函數(shù),參數(shù)就是context(我們的上下文數(shù)據(jù)) {username,setUsername}=context,進(jìn)行了es6語法結(jié)構(gòu)*/}
         
            {({username,setUsername})=>{
                return <p onClick={()=>{setUsername('王老五')}}>{username}</p>
            }}
        </Consumer>
    );
}

export default Son;

這樣就通過了A組件到C組件之間的數(shù)據(jù)傳遞

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容