创建一个状态管理组件 color.tsx
import React, { createContext, useReducer } from 'react';
export const ColorContext = createContext({});
export const UPDATE_COLOR = 'UPDATE_COLOR';
const reducer = (state: any, action: any) => {
switch (action.type) {
case UPDATE_COLOR:
return action.color;
default:
return state;
}
};
export const Color = (props: any) => {
const [color, dispatch] = useReducer(reducer, 'blue');
return (
<ColorContext.Provider value={{ color, dispatch }}>
{props.children}
</ColorContext.Provider>
);
};
创建一个button组件 buttons.tsx
import React, { useContext } from 'react';
import { ColorContext, UPDATE_COLOR } from './color';
const Buttons = () => {
const { dispatch } = useContext(ColorContext) as any;
return (
<React.Fragment>
<button
onClick={() => {
dispatch({ type: UPDATE_COLOR, color: 'red' });
}}
>
红色
</button>
<button
onClick={() => {
dispatch({ type: UPDATE_COLOR, color: 'yellow' });
}}
>
黄色
</button>
</React.Fragment>
);
};
export default Buttons;
创建一个showArea.tsx
import React, { useContext } from 'react';
import { ColorContext } from './color';
const ShowArea = () => {
const { color } = useContext(ColorContext) as any;
return (
<div style={{ color }}>字体颜色展示为{color}</div>
);
};
export default ShowArea;
主文件 index.tsx
import React from 'react';
import { Color } from './color';
import ShowArea from './ShowArea';
import Buttons from './buttons';
export default () => {
return (
<Color>
<ShowArea />
<Buttons />
</Color>
)
}