乐趣区

关于前端:react-hooks-useContext-实现父子组件通讯

明天接触了一下 hooks , 的确感觉相比 class 组件要轻量及很多, 霎时爱上了~
我来说一下应用 useContext 时实现父子组件通信问题, 贴上我 demo 的代码~
先贴上我用到的三个文件

父组件 App.js

import React, {useState} from 'react'
import CountContext from './CountContext'
import Counter from './Counter'

export default function App() {const [ count, setCount] = useState(0)
  return (
    <div>
      <p> 计数器值为:{count}</p>
      <button onClick={() => setCount(count+1)}> 点我加一 </button>
      <CountContext.Provider value={count}>
        <Counter />
      </CountContext.Provider>
    </div>
  )
}

子组件 Counter.jsx

import React, {useContext} from 'react'
import CountContext from './CountContext'

export default function Counter() {let count = useContext(CountContext)
  return (<h2>{count}</h2>
  )
}

公共组件 CountContext.jsx

import {createContext} from "react";

const CountContext = createContext(null)
export default CountContext

退出移动版