網站首頁 編程語言 正文
一、概述
- Context 提供了一個無需為每層組件手動添加 props,就能在組件樹間進行數據傳遞的方法。
- 如果多個組件中都需要這個值 或者 獲取值和使用值的層級相隔很遠,就可以使用Context(上下文)來共享數據。
- 如:地區偏好,UI 主題、當前認證的用戶、語言等
- 謹慎使用,這會使組件的復用性變差
二、API
React.createContext
const MyContext = React.createContext(defaultValue)
- 創建一個 Context 對象
- 提供一個默認值,只有當組件所處的樹中沒有匹配到 Provider 時,其 defaultValue 參數才會生效
Context.Provider
const MyContext = React.createContext(defaultValue)
<MyContext.Provider value={xxx}> ... </MyContext.Provider>
- 每個 Context 對象都會返回一個 Provider React 組件
- Provider 接收一個 value 屬性,傳遞給消費組件。一個 Provider 可以對應多個消費組件。多個 Provider 也可以嵌套使用,里層的會覆蓋外層的數據
- value 值發生變化時,它內部的所有消費組件都會重新渲染
Class.contextType
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* 在組件掛載完成后,使用 MyContext 組件的值來執行一些有副作用的操作 */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* 基于 MyContext 組件的值進行渲染 */
}
}
MyClass.contextType = MyContext;
- 掛載在 class 上的 contextType 屬性會被重賦值為一個由 React.createContext() 創建的 Context 對象
- 可以在任意生命周期中訪問
Context.Consumer
<MyContext.Consumer>
{value => /* 基于 context 值進行渲染*/}
</MyContext.Consumer>
- 消費組件(子組件)中使用value
- 函數作為子元素;這個函數接收當前的 context 值,返回一個 React 節點。傳遞給函數的 value 值等同于往上組件樹離這個 context 最近的 Provider 提供的 value 值。如果沒有對應的 Provider,value 參數等同于傳遞給 createContext() 的 defaultValue。
Context.displayName
const MyContext = React.createContext()
MyContext.displayName = 'MyDisplayName'
<MyContext.Provider> //在 DevTools 中顯示的標簽:MyDisplayName.Provider
<MyContext.Consumer>//在 DevTools 中顯示的標簽:MyDisplayName.Consumer
//如果沒有 MyContext.displayName = 'MyDisplayName' ,則顯示Context.Provider、Context.Consumer
在 DevTools 中需要顯示的內容
三、使用
1.自定義Context (類組件中使用)
//ThemeContext.js
import React from 'react'
export const ThemeContext = React.createContext('light')
//themed-button.js
//在需要的位置使用 Class.contextType
import React, { Component } from 'react';
import ThemeContext from "./context/ThemeContext.js";
class ThemedButton extends Component {
static contextType = ThemeContext;
render() {
return <button>{this.context}</button>;
}
}
export default ThemedButton
//app.js
//上下文包裹組件 Context.Provider
import ThemeContext from './context/ThemeContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
function App() {
return (
<ThemeContext.Provider value='dark'> //dark將默認值light覆蓋
<div className="App">
<header className="App-header">
<ThemedButton />
</header>
</div>
</ThemeContext.Provider>
);
}
export default App;
2.使用Consumer支持獲取多個Context上的值
需要多個上下文的值時可以使用Consumer
//ThemeContext.js
import React from 'react'
const ThemeContext = React.createContext('light')
ThemeContext.displayName = 'ThemeContext'
export default ThemeContext
//UserContext.js
import React from 'react'
const UserContext = React.createContext('guest')
UserContext.displayName = 'UserContext'
export default UserContext
//app.js
//使用Provider賦值:
import React, { Component } from 'react';
import ThemeContext from './context/ThemeContext.js';
import UserContext from './context/UserContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ThemeContext.Provider value={'dark'}>
<div className="App">
<UserContext.Provider value={'user'}>
<header className="App-header">
<ThemedButton />
</header>
</UserContext.Provider>
</div>
</ThemeContext.Provider>
);
}
}
export default App
//themed-button.js
import React, { Component } from 'react';
import ThemeContext from "./context/ThemeContext.js";
import UserContext from "./context/UserContext.js";
class ThemedButton extends Component {
render() {
return (
<>
<ThemeContext.Consumer>
{theme => <div>{theme}</div>}
</ThemeContext.Consumer>
<UserContext.Consumer>
{user => <div>{user}</div>}
</UserContext.Consumer>
</>
);
}
}
export default ThemedButton
3.useContext使用(函數式組件中使用)
react原生Hook ,讓函數式組件也可以使用Context,而且支持多個不同類型的context
//ThemeContext.js
import React from 'react'
const ThemeContext = React.createContext('light')
ThemeContext.displayName = 'ThemeContext'
export default ThemeContext
//UserContext.js
import React from 'react'
const UserContext = React.createContext('guest')
UserContext.displayName = 'UserContext'
export default UserContext
//app.js
//使用Provider賦值:
import React, { Component } from 'react';
import ThemeContext from './context/ThemeContext.js';
import UserContext from './context/UserContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
const App = () => {
render() {
return (
<ThemeContext.Provider value={'dark'}>
<div className="App">
<UserContext.Provider value={'user'}>
<header className="App-header">
<ThemedButton />
</header>
</UserContext.Provider>
</div>
</ThemeContext.Provider>
);
}
}
export default App
//themed-button.js
import { useContext } from 'react'
import ThemeContext from './context/ThemeContext'
import UserContext from './context/UserContext'
const ThemedButton = () => {
const theme = useContext(ThemeContext)
const user = useContext(UserContext)
return (
<>
<div>{theme}</div>
<div>{user}</div>
</>
)
}
export default ThemedButton
原文鏈接:https://blog.csdn.net/xbczrz/article/details/127983897
相關推薦
- 2024-03-25 解決idea配置自定義的maven失敗的問題
- 2022-11-14 Python?prettytable模塊應用詳解_python
- 2022-07-18 Linux文件系統和日志分析
- 2022-02-23 C#使用log4net記錄日志_C#教程
- 2022-11-29 將VSCode添加至右鍵的菜單欄
- 2022-09-13 Go語言對前端領域的入侵WebAssembly運行原理_Golang
- 2022-06-01 C#中內聯函數的用法介紹_C#教程
- 2023-06-21 python相對包導入報“Attempted?relative?import?in?non-pack
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支