便于我们对context的使用。从上向下进行数据的传递。也就是再根组件上传递数据,在任意的子组件中都可以获取到根组件传递过来的数据。可以直接进行使用。useContext简化了我们使用context的过程,实际上原理还是一样的。
1、案例:从父组件向子孙组件传递数据
import React, { createContext } from 'react'import ReactDOM from 'react-dom'// 使用useContext 进行状态的传递import App from './20_hooks的使用/05_useContext的使用'// 定义context以及需要传递的数据 同时进行导出 提供给其他的组件使用export const UserContext = createContext()export const ThemeContext = createContext()// 原始的渲染方法// ReactDOM.render(// <App />,// document.getElementById('root')// )// 使用context的渲染的方法 在组件中进行使用 最外层的两个context都向App组件传递数据ReactDOM.render(<UserContext.Provider value={{ name: 'coderweiwei', age: 123 }}><ThemeContext.Provider value={{color: 'pink', fontSize: '16px' }}><App /></ThemeContext.Provider></UserContext.Provider>,document.getElementById('root'))
2、子组件使用父组件传递的数据
import React, { useContext } from 'react'// 先引入需要传递的context 然后使用相应的context hookimport { UserContext, ThemeContext } from '../index'export default function ContextHookDemo() {// 使用useContext钩子函数const user = useContext(UserContext)const theme = useContext(ThemeContext)// 在子组件中直接使用即可console.log(user, theme);return (<div><h2>context的具体使用</h2></div>)}# 可以封装为自定义的hook函数 提供给具体的业务组件进行使用
3、useContext的使用规则总结
useContext就是用来简化我们原来使用原生的context的繁琐步骤,可以简单的将其理解为原生useContext的语法糖形式。使用规则:在项目的根组件中创建我们需要传递的context。const UserContext = createContext();const ThemeContext = createContext();将创建的context实例映射为react组件的标签 并通过标签的形式向子孙组件传递数据。<UserContext.Provider value={{ name: "weiwei", age: 18 }}><ThemeContext value={{ color: "red"; fontSize: "12px"; }}>// 将根组件放入 这样的话我们需要的数据就传递下去了 任意的子组件就可以获取我们的数据了<App /><ThemeContext><UserContext.Prpvider>在任意的组件中进行使用contextimport { useContext } from "react";// 引入我们需要的contextimport { UserContext, ThemeContext } from "./App.js";const user = useContext(UserContext);const theme = useContext(ThemeContext);// 这里就可以获取我们的数据了 可以直接使用传递的context的值了 直接可以在组件的内部进行使用console.log(user,theme)
