Hooks useContext 实例(小demo)

  唉,看了几片关于hooks useContext的文章,除了千篇一律的抄文档,还是抄,估计自己都没明白吧

本人脑子笨,写个简单的demo记录一下,防止以后忘了

结构

 

注意分级,别到时候路径没写对又找我事儿

 

 

 

 

 

废话不多说,上代码

globalContext.js

import React from "react";

// 创建一个useContext,用的时候直接引入
export const GlobalContext = React.createContext()

GrandFather.js

import React from "react";
import Father from './Father';
import { GlobalContext } from '../globalContext';

// 跨组件传递的内容
const grandFatherValue = {
  name:"我是GrandFather的值",
  target:"我想把GrandFather的值通过useContext传递给Children那个孙子组件"
}
//最外层组件
const GrandFather = () => {
  
  return (
    <GlobalContext.Provider value={{...grandFatherValue}}>
      <h1>GrandFather组件</h1>
      <Father />
    </GlobalContext.Provider>
  )
}

export default GrandFather ;
Father.js
import React from "react";
import Children from './Children';

//中间组件,啥都不用干
const Father = () => {
  
  return (
    <div>
      <h3>Father组件</h3>
      <Children />
    </div>
  )
}

export default Father ;

Children.js

import React, { useContext } from "react";
import { GlobalContext } from '../globalContext';

//最内层组件
const Children = () => {
  
  // 接受GrandFather跨组件(跨Father组件)传递的值
  const value = useContext(GlobalContext);

  console.log("接收到的数据:",value)
  return (
    <div>
      <h5 >Children组件</h5>
    </div>
  )
}

export default Children;

页面效果

 

 打印效果

 

 

posted @ 2021-09-03 11:10  HandsomeGuy  阅读(185)  评论(0编辑  收藏  举报