likes
comments
collection
share

react中Context 的使用

作者站长头像
站长
· 阅读数 43

react 中 context 为解决跨组件通信问题 父组件通过 context.Provider 提供数据

孙子组件通过 useContext 进行使用

App.tsx
import { useState } from "react"
import Home from "./components/Home"
// 引入 创建的 context
import ThemeContext from "./context"
import { ThemeContextTypes } from "./data"
const App = () => {
  const [ThemeParams, setThemeParams] = useState<ThemeContextTypes>({ color: 'blue', size: 30 })
  /* APP 组件提供数据 */
  return (
    <div>
      <ThemeContext.Provider value={ThemeParams}>
        <div>app</div>
        <Home />
      </ThemeContext.Provider>

    </div>
  )
}

export default App 

context.ts

import React from "react";
// 创建一个上下文 
const ThemeContext = React.createContext({ color: 'red', size: 30 })

export default ThemeContext

Home.tsx

import HomeProduct from "./HomeProduct"

const Home = () => {

  return (
    <div>
      <HomeProduct></HomeProduct>
    </div>
  )
}

HomeProduct.tsx

export default Home 
import { useContext } from "react"
import ThemeContext from "../context"
import { ThemeContextTypes } from "../data"

const HomeProduct = () => {
  const context: ThemeContextTypes = useContext(ThemeContext)
  return (
    <div>
      <div>{context.color}</div>
      <p>大小{context.size}</p>
    </div>
  )
}

export default HomeProduct 
转载自:https://juejin.cn/post/7177349481715744829
评论
请登录