hook中使用redux

126 阅读1分钟

创建一个状态管理组件 color.tsx

import React, { createContext, useReducer } from 'react';

// 创建 context
export const ColorContext = createContext({});

// reducer
export const UPDATE_COLOR = 'UPDATE_COLOR';


const reducer = (state: any, action: any) => {
  switch (action.type) {
    case UPDATE_COLOR:
      return action.color;
    default:
      return state;
  }
};

/**
 * 创建一个 Color 组件
 * Color 组件包裹的所有组件都可以访问到 value
 */

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>
      )

}