其他分享
首页 > 其他分享> > createContext、useContext

createContext、useContext

作者:互联网

父组件

import React,{FC,createContext, useContext,useState} from "react";
import Counter from "./components";

export const MyContext = createContext(0);
const Test:FC = () => {
  const [count,setCount] = useState(0)
  return (
    <>
      <div>数值是:{count}</div>
      <button onClick={()=>{setCount(count+1)}}>我是按钮</button>

      <MyContext.Provider value={count}>
        <Counter />
      </MyContext.Provider>
    </>
  )
}

export default Test
父组件

子组件

import React,{FC,createContext, useContext,useState} from "react";
import {MyContext} from '../index';

const Counter:FC = () => {
  const count = useContext(MyContext)
  return (
    <>
      <div>这是{count}</div>
    </>
  )
}

export default Counter
子组件

标签:createContext,count,const,FC,useContext,import
来源: https://www.cnblogs.com/isRs/p/15319621.html