ReactJS - getChildContext() 方法



getChildContext() 函式是 React 中的元件生命週期函式。此函式允許父元件與其子元件交換指定的資訊。它類似於建立一個特定的盒子(上下文),父元件可以在其中儲存重要資料。父元件決定放入盒子中的內容,並允許子元件訪問它,而無需透過使用 getChildContext() 直接傳遞。這種通訊方式使事情井然有序,並簡化了應用程式不同部分之間如何相互通訊,類似於一個家庭有一種特定的方式來討論關鍵資訊,而無需單獨與每個成員溝通。

語法

getChildContext()

為了使用 getChildContext(),元件必須定義一個名為 childContextTypes 的靜態屬性,該屬性指定上下文資料的預期型別。

示例

示例 1

讓我們使用 getChildContext() 函式建立一個示例。在這個例子中,我們將建立一個簡單的應用程式,透過上下文傳遞使用者資料來顯示使用者資訊。

import PropTypes from 'prop-types';
import React, { Component } from 'react';

// Create a context
const UserContext = React.createContext({
   username: 'Guest',
   age: 0,
});

// Create a component
class UserProvider extends Component {
   // Define child context types
   static childContextTypes = {
      user: PropTypes.shape({
      username: PropTypes.string,
      age: PropTypes.number,
   }),
   };   
   getChildContext() {
      return {
         user: {
            username: this.props.username,
            age: this.props.age,
         },
      };
   }
   
   render() {
      // Render the child components
      return this.props.children;
   }
}

// Create a component that consumes user data from context
class UserInfo extends Component {
   static contextTypes = {
      user: PropTypes.shape({
         username: PropTypes.string,
         age: PropTypes.number,
      }),
   };   
   render() {
      return (
         <div>
            <p>Welcome, {this.context.user.username}!</p>
            <p>Your age: {this.context.user.age}</p>
         </div>
      );
   }
}

// Create the main App component
class App extends Component {
   render() {
      return (
         // Wrap the UserInfo component with the UserProvider
         <UserProvider username="Amit" age={25}>
            <UserInfo />
         </UserProvider>
      );
   }
}

export default App;

輸出

welcome amit

在上面的程式碼中,App 元件使用 UserProvider 包裝 UserInfo 元件,以透過上下文傳遞使用者資料。

示例 2

這是一個使用 getChildContext() 在 React 應用中建立簡單主題上下文的另一個示例 -

import React, { Component } from 'react';
import PropTypes from 'prop-types';

// Create a context for the theme
const ThemeContext = React.createContext({
   theme: 'light',
   toggleTheme: () => {},
});

// Create a component for providing the theme
class ThemeProvider extends Component {
   
   // Define child context types
   static childContextTypes = {
      themeContext: PropTypes.shape({
         theme: PropTypes.string,
         toggleTheme: PropTypes.func,
      }),
   };
   
   // Set initial state
   state = {
      theme: 'light',
   };
   
   // Define a function to toggle the theme
   toggleTheme = () => {
      this.setState((prevState) => ({
         theme: prevState.theme === 'light' ? 'dark' : 'light',
      }));
   };
   
   // Provide the theme context through getChildContext()
   getChildContext() {
      return {
         themeContext: {
            theme: this.state.theme,
            toggleTheme: this.toggleTheme,
         },
      };
   }
   
   render() {
      // Render the child components
      return this.props.children;
   }
}

// Create a component
class ThemedComponent extends Component {
   // Define context types
   static contextTypes = {
      themeContext: PropTypes.shape({
         theme: PropTypes.string,
         toggleTheme: PropTypes.func,
      }),
   };
   
   render() {
      return (
         <div style={{ background: this.context.themeContext.theme === 'light' ? '#fff' : '#333', color: this.context.themeContext.theme === 'light' ? '#333' : '#fff' }}>
            <p>Current Theme: {this.context.themeContext.theme}</p>
            <button onClick={this.context.themeContext.toggleTheme}>Toggle Theme</button>
         </div>
      );
   }
}

// Create the main App component
class ThemeApp extends Component {
   render() {
      return (
         <ThemeProvider>
            <ThemedComponent />
         </ThemeProvider>
      );
   }
}

export default ThemeApp;

輸出

current theme

在上面的示例中,ThemeProvider 元件使用 getChildContext() 提供一個主題上下文,預設主題為“light”,並提供一個切換主題的函式。ThemedComponent 然後使用此上下文顯示有關當前主題的資訊和一個切換按鈕。ThemeApp 元件在 ThemeProvider 的上下文中渲染 ThemedComponent。

示例 3

讓我們再建立一個使用 getChildContext() 在 React 應用中管理使用者身份驗證的示例 -

import React, { Component } from 'react';
import PropTypes from 'prop-types';

// Create a context for user authentication
const AuthContext = React.createContext({
   isAuthenticated: false,
   login: () => {},
   logout: () => {},
});

// Create a component for providing authentication context
class AuthProvider extends Component {
   static childContextTypes = {
      authContext: PropTypes.shape({
         isAuthenticated: PropTypes.bool,
         login: PropTypes.func,
         logout: PropTypes.func,
      }),
   };
   
   // Set initial state
   state = {
      isAuthenticated: false,
   };
   
   // Define a function to handle user login
   login = () => {
      this.setState({
         isAuthenticated: true,
      });
   };
   
   // Define a function to handle user logout
   logout = () => {
      this.setState({
         isAuthenticated: false,
      });
   };
   
   // Provide the authentication context through getChildContext()
   getChildContext() {
      return {
         authContext: {
            isAuthenticated: this.state.isAuthenticated,
            login: this.login,
            logout: this.logout,
         },
      };
   }
   
   render() {
      // Render the child components
      return this.props.children;
   }
}

// Create a component that consumes the authentication context
class AuthComponent extends Component {
   // Define context types
   static contextTypes = {
      authContext: PropTypes.shape({
         isAuthenticated: PropTypes.bool,
         login: PropTypes.func,
         logout: PropTypes.func,
      }),
   };
   
   render() {
      return (
         <div>
            <p>User is {this.context.authContext.isAuthenticated ? 'authenticated' : 'not authenticated'}</p>
            {this.context.authContext.isAuthenticated ? (
               <button onClick={this.context.authContext.logout}>Logout</button>
            ) : (
               <button onClick={this.context.authContext.login}>Login</button>
            )}
         </div>
      );
   }
}

// Create the main App component
class App extends Component {
   render() {
      return (
         <AuthProvider>
            <AuthComponent />
         </AuthProvider>
      );
   }
}

export default App;

輸出

aunthenticated user

在上面的應用程式中,AuthProvider 元件使用 getChildContext() 提供一個身份驗證上下文,其預設值為 isAuthenticated 設定為 false。它還具有管理登入和登出操作的功能。AuthComponent 使用此上下文來確定使用者是否已認證,並提供登入和登出按鈕。

侷限性

從 React 16.3 開始,getChildContext() 函式已棄用,建議使用新的 Context API 來代替。

總結

getChildContext() 函式可用於在 React 元件中提供上下文,建議開發人員採用新的 Context API 以提高可讀性和未來的相容性。

reactjs_reference_api.htm
廣告