React Hook 实现 redux 状态管理

// HookFunction.tsx
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;
// Color.tsx
import * as React from 'react';

export const ColorContext = React.createContext({});

// actionTypes
export const UPDATE_COLOR = 'UPDATE_COLOR';

// reducer
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>
    </>
  )
};
// HookShowArea.tsx
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;
// HookOperateButton.tsx
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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值