在React中背景關系是一種通信方案,
背景關系的特點
- 在組件樹中,是一種自上而下的單向資料流通信方案,資料只能從父組件注入,在子組件中訪問,
- 組件關系只要滿足“父組件-后代組件”這種關系時,都可以使用背景關系通信,
- 在父組件中provide提供資料,在后代組件中注入并使用,這種通信不具有回應式,有點像vue中的provide/inject通信,
如何使用背景關系
-
使用 const{Provider,Consumer} = Raact.createContext() 創建背景關系,
-
使用 <Provider value=https://www.cnblogs.com/wang622/archive/2022/08/16/{}> 向組件樹中提供資料,
-
在后代組件中使用<Consumer>{(context)=>(jsx/)}</Consumer>訪問背景關系資料,
- 如果后代組件是類組件,可以使用 Page.contextType = ThemeContext 訪問背景關系資料,
使用背景關系穿透和背景關系通信的區別
- props穿透必須清楚組件之間的關系,背景關系只要滿足“父組件-后代組件”關系,
- props適合父子關系明顯的組件通信,背景關系關系適合父子關系不明確的組件通信,
- props穿透會導致后代組件的props變得臃腫,背景關系通信更加直接方便,
背景關系通信在那些場景遇到
- 路由中會用到背景關系通信
- 狀態管理中
- 組件庫中,切換主題色,切換組件大小等
- 國際化中
使用背景關系封裝拾色器
import { PureComponent, useState } from "react"
//創建背景關系物件
const ThemeContext = React.createContext()
const{Consumer,Provider} = ThemeContext
class App extends PureComponent{
render(){
return(
<Consumer>
{
(context) => {
console.log(context)
return(
<div style={context}>
<h1>555</h1>
</div>
)
}
}
</Consumer>
)
}
}
//封裝拾色器
function ThemeToggle({value, onChange}){
const change = (ev) =>{
const key = ev.target.name
// console.log('key',key);
const val = ev.target.value
// console.log('val',val);
//把變化后的主題色回傳給父組件
onChange({...value, [key]:val})
}
return(
<>
<div>
<label >前景色</label>
<input type="color" name="color" value=https://www.cnblogs.com/wang622/archive/2022/08/16/{value.color} onChange={change} />
