【React】hooks 之 useContext

1 useState
2 useEffect
3 useContext
4 useReducer


3 useContext() shared state hook

useContextThe role of is to achieve data sharing, solve the problem of passing values ​​between components, and directly pass variables across component levels. That is, a technology that provides global shared data for the component tree it contains.

3.1 Create Context

The root component introduces createContextthe method and creates a Context

import React, {
    
     createContext } from 'react';

const ContextName = createContext();

3.2 Passing values ​​to descendant components

Use ContextName.Providerthe component the descendant components that need to accept data,

And provide the data to share via valuethe attribute .

<ContextName.Provider value={
    
    count}>
    <Child />
</ContextName.Provider>

3.3 Descendant components get the value passed in

Use in descendant components to get the value passed in useCountextby the root component,

useContextPass the defined in the root component toContextName

import React, {
    
     useContext } from 'react';

const Child = () => {
    
    
  const count = useContext(ContextName);
  return <p>子组件获得的点击数量:{
    
    count}</p>;
};

3.4 Complete example

import React, {
    
     useState, createContext, useContext } from "react";
const ContextName = createContext();

const Child = () => {
    
     // 后代组件
  const count = useContext(ContextName);
  return <p>子组件获得的点击数量:{
    
    count}</p>;
};

const Parent = () => {
    
     // 根组件
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>父组件点击数量:{
    
    count}</p>
      <button onClick={
    
    () => setCount(count + 1)}>{
    
    "点击+1"}</button>
      <ContextName.Provider value={
    
    count}>
        <Child />
      </ContextName.Provider>
    </div>
  );
};

export default Parent;

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/125783183