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)
使用步驟
- 創(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}
- 創(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;
- 創(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ù)傳遞