react-redux简单计算器

时间:2017-06-19 19:06:55

标签: reactjs redux react-redux

react-redux的新功能(与typescipt一起使用)。我正在尝试为firstNum和secondNum创建一个带有两个文本字段的简单计算器,并让它显示输出。只有三个按钮,添加乘法和减法。请帮助,我不知道如何处理文本框,也不知道如何正确显示输出。

容器:

import * as React from 'react';
import { mult, add, sub } from 'modules/counter/';
import { ICounter } from 'models/counter';
import { ICounterAction } from 'models/counter';
const { connect } = require('react-redux');
const style = require('./style.css');

interface IProps {
  firstNum: ICounter;
  secondNum: ICounter;
  out: ICounter;
  mult: Redux.ActionCreator<ICounterAction>;
  add: Redux.ActionCreator<ICounterAction>;
  sub: Redux.ActionCreator<ICounterAction>;
}

@connect(
  (state) => ({ firstNum: state.firstNum, secondNum: state.secondNum, out: state.out }),
  (dispatch) => ({
    mult: () => dispatch(mult()),
    add: () => dispatch(add()),
    sub: () => dispatch(sub()),
  }),
)

class Counter extends React.Component<IProps, void> {
  public render() {
    const { mult, add, sub, out, secondNum, firstNum} = this.props;

    return (
      <div className={style.Counter}>
        <h4>MarkSlav</h4>
        <button
          name="multBtn"
          onClick={mult}>
          MULT
        </button>
        <button
          name="addBtn"
          onClick={add}>
          ADD
        </button>
        <button
          name="subBtn"
          onClick={sub}>
          SUB
        </button>
        <p>{out}</p>
        <p>{secondNum}</p>
        <p>{firstNum}</p>
      </div>
    );
  }
}

export { Counter }

reducer:

import { ICounter, ICounterAction } from 'models/counter';

/** Action Types */
export const MULT: string = 'counter/MULT';
export const ADD: string = 'counter/ADD';
export const SUB: string = 'counter/SUB';

/** Counter: Initial State */
const initialState: ICounter = {
  firstNum: 0,
  secondNum: 0,
  out: 0,
};

/** Reducer: CounterReducer */
export function counterReducer(state = initialState, action?: ICounterAction) {
  switch (action.type) {
    case MULT:
      return {
        out: state.firstNum * state.secondNum,
      };
    case ADD:
      return {
        out: state.firstNum + state.secondNum,
      };
    case SUB:
      return {
        out: state.firstNum - state.secondNum,
      };

    default:
      return state;
  }
}

  export function mult(): ICounterAction {
  return {
    type: MULT,
  };
}
  export function add(): ICounterAction {
  return {
    type: ADD,
  };
}

  export function sub(): ICounterAction {
  return {
    type: SUB,
  };
}

模型:

export interface ICounter {
  out: number;
  firstNum: number;
  secondNum: number;
}

export interface ICounterAction {
  type: string;
}

0 个答案:

没有答案