新建一个example文件夹,用来存放小demo的所有js文件
开始写代码
showArea.js 上面的显示部分
import React,{useContext} from 'react';
import {ColorContext} from './color.js'
function ShowArea(){
const {color} = useContext(ColorContext)
return(
<div style={{color:color}}>
字体颜色为{color}
</div>
)
}
export default ShowArea;
button.js下面的按钮点击部分
import React,{useContext} from 'react';
import {ColorContext,UPDATE_COLOR} from './color'
function Button(){
const {dispatch} = useContext(ColorContext);
return(
<div>
<button onClick={()=>{dispatch({type:UPDATE_COLOR,color:"yellow"})}}>黄色</button>
<button onClick={()=>{dispatch({type:UPDATE_COLOR,color:"red"})}}>红色</button>
</div>
)
}
export default Button;
最后组合起来
Example7.js
import React from 'react';
import ShowArea from './showArea.js'
import Button from './Button.js'
import {Color} from './color.js'
function Example7(){
return(
<div>
<Color >
<ShowArea />
<Button />
</Color>
</div>
)
}
export default Example7;
具体实现功能color.js
import React,{createContext,useReducer} from 'react';
export const ColorContext = createContext()
export const UPDATE_COLOR ="update_color";
const reducer = (state,action)=>{
switch(action.type){
case UPDATE_COLOR:
return action.color
default :
return state
}
}
export const Color = props=>{
const [color,dispatch]= useReducer(reducer,'blue');
return(
<ColorContext.Provider value={{color,dispatch}}>
{props.children}
</ColorContext.Provider>
)
}