ReactJS - static contextType 屬性



React 中的 Context API 幫助我們快速處理和共享應用程式中的狀態。因此,我們將瞭解如何在 React 類元件中使用 static contextType 來讀取和使用上下文資料。

React 中的 Context 是一種在元件之間傳遞資料的方法,無需透過元件樹的每一層傳遞 props。這對於共享資料(如主題、使用者身份驗證或不同元件需要訪問的任何全域性資訊)非常有用。

語法

const MyContext = React.createContext();

首先,我們需要使用 React.createContext() 建立一個上下文。這將是我們想要在元件中訪問的上下文。

如何使用它?

要使用 Context API,我們可以按照以下步驟操作:

  • 首先我們需要建立上下文。我們可以使用 createContext 函式來建立上下文。

  • 接下來,我們將使用 Context Provider 包裝元件樹,以便為需要它的元件提供上下文。

  • 要在函式元件中訪問上下文的值,我們將使用 useContext hook。要在類元件中訪問上下文,我們可以使用 static contextType 屬性。

示例

示例

在這個應用程式中,我們將顯示使用者是否已透過身份驗證。因此,我們將有一個 App 元件來管理使用者身份驗證的狀態(true 或 false)。它將使用 AuthContext.Provider 將身份驗證狀態提供給其子元件。然後,我們將建立一個 AuthStatus 元件,它將使用 static contextType 來訪問身份驗證上下文。我們將根據使用者是否登入顯示訊息。

import React, { createContext, Component } from 'react';

const AuthContext = createContext();
class App extends Component {
   state = {
      isAuthenticated: true,
   };   
   render() {
      return (
         <AuthContext.Provider value={this.state.isAuthenticated}>
         <AuthStatus />
         </AuthContext.Provider>
      );
   }
}
class AuthStatus extends Component {
   static contextType = AuthContext;   
   render() {
      const isAuthenticated = this.context;   
      return (
         <div>
            <h1>User Authentication App</h1>
            {isAuthenticated ? <p>User is logged in</p> : <p>User is not logged in</p>}
         </div>
      );
   }
}

export default App;

輸出

user authentication app

因此,我們可以看到使用者已登入,因為我們將 isAuthenticated 狀態設定為 true。如果我們將其設定為 false,則它將顯示訊息“使用者未登入”。

示例 - 語言選擇應用程式

在這個應用程式中,我們將具有允許使用者選擇其首選語言的功能。因此,我們將有一個 App 元件。此元件將管理所選語言的狀態。它還將使用 LanguageContext.Provider 將語言狀態提供給其子元件。然後,我們將擁有另一個名為 LanguageSelector 的元件,該元件將使用 static contextType 來訪問語言上下文。它將呈現一個簡單的 UI,顯示所選語言。

import React, { createContext, Component } from 'react';

const LanguageContext = createContext();
class App extends Component {
   state = {
      language: 'English',
   };   
   render() {
      return (
         <LanguageContext.Provider value={this.state.language}>
            <LanguageSelector />
         </LanguageContext.Provider>
      );
   }
}

class LanguageSelector extends Component {
   static contextType = LanguageContext;   
   render() {
      const language = this.context;   
      return (
         <div>
            <h1>Language Selection App</h1>
            <p>Selected Language: {language}</p>
         </div>
      );
   }
}

export default App;

輸出

language selection app

因此,我們可以看到上面顯示的輸出,其中所選語言為英語。因此,我們可以根據使用者的需要更改語言。

示例 - 使用 static contextType 的類元件

static contextType 屬性可用於在類元件中獲取上下文。我們可以使用一個按鈕建立一個簡單的示例,這樣我們就可以在亮色和暗色主題之間切換,從而允許我們動態更改主題。

import React, { Component } from 'react';

// Create a context
const ThemeContext = React.createContext();
class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         theme: 'light', // Initial theme is light
      };
   }   
   toggleTheme = () => {
      // Update the context value 
      this.setState((prevState) => ({
         theme: prevState.theme === 'light' ? 'dark' : 'light',
      }));
   };   
   render() {
      return (
         <ThemeContext.Provider value={this.state.theme}>
         <div>
            <Button onClick={this.toggleTheme}>Toggle Theme</Button>
         </div>
         </ThemeContext.Provider>
      );
   }
}
class Button extends Component {
   
   // Specify the context
   static contextType = ThemeContext;
   
   render() {
      // Access the context value
      const theme = this.context;
      const className = 'button-' + theme;
   
      return (
         <button className={className} onClick={this.props.onClick}>
            {this.props.children}
         </button>
      );
   }
}

export default App;

當我們點選“切換主題”按鈕時,主題將在亮色和暗色之間動態切換,按鈕的樣式也會相應更改。

總結

static contextType 屬性是在 React 類元件中使用上下文的一種簡單方法,因為它提供了一種簡單的方法來獲取上下文資訊。如果我們的元件需要,我們可以透過宣告上下文來減少程式碼量。使用 static contextType,我們可以更輕鬆地維護全域性狀態並在應用程式中交換資料。

reactjs_reference_api.htm
廣告

© . All rights reserved.