import * as React from 'react' ;
import HookShowArea from './HookShowArea' ;
import HookOperateButton from './HookOperateButton' ;
import { Color } from './Color' ;
const HookFunction = ( ) => {
return (
< >
< div>
< Color>
< HookShowArea / >
< HookOperateButton / >
< / Color>
< / div>
< / >
)
} ;
export default HookFunction;
import * as React from 'react' ;
export const ColorContext = React. createContext ( { } ) ;
export const UPDATE_COLOR = 'UPDATE_COLOR' ;
const colorReducer = ( state, action) => {
switch ( action. type) {
case UPDATE_COLOR :
return action. color;
default :
return state;
}
} ;
export const Color = props => {
const [ color, dispatch ] = React. useReducer ( colorReducer, 'blue' ) ;
return (
< >
< ColorContext. Provider value= { { color, dispatch } } >
{ }
{ props. children }
< / ColorContext. Provider>
< / >
)
} ;
import * as React from 'react' ;
import { ColorContext } from './Color' ;
const HookShowArea = ( ) => {
const { color } : any = React. useContext ( ColorContext) ;
return (
< >
< div>
< p style= { { color } } > 字体颜色为{ color } < / p>
< / div>
< / >
)
} ;
export default HookShowArea;
import * as React from 'react' ;
import { Button } from 'antd' ;
import { UPDATE_COLOR } from './Color' ;
import { ColorContext } from './Color' ;
const HookOperateButton = ( ) => {
const { dispatch } : any = React. useContext ( ColorContext) ;
return (
< >
< div>
< Button type= "danger" onClick= { ( ) => dispatch ( { type: UPDATE_COLOR , color: 'red' } ) } > 红色< / Button>
< Button type= "default" onClick= { ( ) => dispatch ( { type: UPDATE_COLOR , color: 'yellow' } ) } > 黄色< / Button>
< Button type= "primary" onClick= { ( ) => dispatch ( { type: UPDATE_COLOR , color: 'blue' } ) } > 蓝色< / Button>
< / div>
< / >
)
} ;
export default HookOperateButton;