import React, { useReducer } from 'react' import './App.css' import ComponentA from './components/ComponentA' import ComponentB from './components/ComponentB' import ComponentC from './components/ComponentC' const initialState = 0 const reducer = (state, action) => { switch (action) { case 'increment': return state + 1 case 'decrement': return state - 1 case 'reset': return initialState default: return state } } export const CountContext = React.createContext() function App() { const [count, dispatch] = useReducer(reducer, initialState) return ( <CountContext.Provider value={{ countState: count, countDispatch: dispatch }} > <div className="App"> {count} <ComponentA /> <ComponentB /> <ComponentC /> </div> </CountContext.Provider> ) } export default App import React, {useContext} from 'react' import { CountContext } from '../App'; //组件A function ComponentA() { const countContext = useContext(CountContext) return ( <div> Component A {countContext.countState} <button onClick={() => countContext.countDispatch('increment')}>Increment</button> <button onClick={() => countContext.countDispatch('decrement')}>Decrement</button> <button onClick={() => countContext.countDispatch('reset')}>Reset</button> </div> ) } export default ComponentA //组件B import React, {useContext} from 'react' import { CountContext } from '../App'; function ComponentB() { const countContext = useContext(CountContext) return ( <div> Component F {countContext.countState} <button onClick={() => countContext.countDispatch('increment')}>Increment</button> <button onClick={() => countContext.countDispatch('decrement')}>Decrement</button> <button onClick={() => countContext.countDispatch('reset')}>Reset</button> </div> ) } export default ComponentB import React, {useContext} from 'react' import { CountContext } from '../App'; //组件C 其他依此类推 function ComponentC() { const countContext = useContext(CountContext) return ( <div> Component F {countContext.countState} <button onClick={() => countContext.countDispatch('increment')}>Increment</button> <button onClick={() => countContext.countDispatch('decrement')}>Decrement</button> <button onClick={() => countContext.countDispatch('reset')}>Reset</button> </div> ) } export default ComponentC