react hooks的useContext

简介:

React 的 useContext Hook 用于在函数组件中获取上下文(Context)的值。它允许我们在组件中订阅并访问由 React 的 Context API 提供的值。

首先,我们需要创建一个上下文对象。上下文对象被创建时,它包含一个 Provider 和一个 Consumer。

在创建上下文对象后,我们可以使用 useContext Hook 在函数组件中订阅上下文的值。

以下是使用 useContext Hook 的一般步骤:

  1. 创建上下文对象:
import React, { createContext } from 'react';

// 创建上下文对象
const MyContext = createContext();

  1. 在顶层组件中通过 Provider 提供上下文的值:
import React from 'react';
import { MyContext } from './MyContext';

function App() {
  return (
    // 使用 Provider 提供上下文的值
    
      
    
  );
}

  1. 在子组件中使用 useContext Hook 获取上下文的值:
import React, { useContext } from 'react';
import { MyContext } from './MyContext';

function ChildComponent() {
  // 使用 useContext Hook 获取上下文的值
  const contextValue = useContext(MyContext);

  return 
{contextValue}
; }

在上面的示例中,我们首先创建了一个名为 MyContext 的上下文对象,并将其导出供其他组件使用。

然后,在根组件 App 中,我们使用 MyContext.Provider 组件提供上下文的值,并将要共享的值传递给 value 属性。

最后,在子组件 ChildComponent 中,我们使用 useContext Hook 来接收 MyContext 上下文对象的值,并将其赋值给 contextValue 变量。然后,我们可以在组件中使用这个值。

需要注意的是,useContext Hook 接收一个上下文对象作为参数,并返回上下文的当前值。它只能在函数组件的顶层中使用,而不能在嵌套的函数或类中使用。

当上下文的值发生变化时,使用 useContext Hook 的组件会自动重新渲染。这使得我们可以便捷地使用 React 的 Context API 来共享和订阅全局状态。

全部代码:

import React, { createContext, useContext } from 'react';
// 使用 useContext 函数可以避免在组件层层传递 props,从而简化了组件之间的数据共享。
// 创建一个 Context 对象
const MyContext = createContext();

// 在组件树中的某个位置提供 Context 的值
function MyProvider(props) {
    const contextValue = {...props.student};

    return {props.children};
}
function Bag() {
    const contextValue = useContext(MyContext);

    return (
        

Bag: {contextValue.bag}

); } // 使用 useContext 来使用 Context 中的值 function MyComponent() { const contextValue = useContext(MyContext); return (

Name: {contextValue.name}

Age: {contextValue.age}

); } // 在组件中使用 Context export default function App() { const [state, setState] = React.useState({ name: 'Tom', age: 18, bag: '两本书 一壶水' }); return ( ); }

你可能感兴趣的:(react.js,javascript,前端)