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
父组件

子组件

createContext、useContext
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
子组件
上一篇:华为S2600存储FC到X86服务器


下一篇:开学测试