Hooks useContext 例項(小demo)
阿新 • • 發佈:2021-09-03
唉,看了幾片關於hooks useContext的文章,除了千篇一律的抄文件,還是抄,估計自己都沒明白吧
本人腦子笨,寫個簡單的demo記錄一下,防止以後忘了
結構
注意分級,別到時候路徑沒寫對又找我事兒
廢話不多說,上程式碼
globalContext.js
import React from "react"; // 建立一個useContext,用的時候直接引入 export const GlobalContext = React.createContext()
GrandFather.js
import React from "react"; import Father fromFather.js'./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> ) } exportdefault GrandFather ;
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;
頁面效果
列印效果