// 仅仅使用redux
import React, { Component } from 'react';
import { Action } from 'redux';
import {Text, TouchableOpacity, View, StyleSheet, TextInput} from 'react-native';
import { store } from './store';
import {addTowNumbers, descTowNumbers, CountActionType} from './action';
const {
DESC,
ADD
} = CountActionType;
type State = {
addResult: number,
descResult: number
};
const styles = StyleSheet.create({
textInput: {
width: 60,
borderRadius: 4,
borderWidth: 0.5,
borderColor: 'gray'
},
tipText: {
}
});
export default class AddTestView extends Component<null, State> {
addFirstNumber: string = '0';
addSecondNumber: string = '0';
descFirstNumber: string = '0';
descSecondNumber: string = '0';
constructor (props: any) {
super(props);
this.state = {
addResult: 0,
descResult: 0
};
store.subscribe(() => {
const {
addResult,
descResult
} = store.getState();
this.setState({ addResult, descResult });
});
}
firstTextChange = (type) => (text) => {
if (type === CountActionType.ADD) {
this.addFirstNumber = text;
this.dispathAddAction();
} else {
this.descFirstNumber = text;
this.dispathDescAction();
}
}
secondTextChange = (type) => (text) => {
if (type === CountActionType.ADD) {
this.addSecondNumber = text;
this.dispathAddAction();
} else {
this.descSecondNumber = text;
this.dispathDescAction();
}
}
dispathAddAction = () => {
const action = addTowNumbers({firstNumber: this.addFirstNumber, secondNumber: this.addSecondNumber});
store.dispatch(action);
}
dispathDescAction = () => {
const action = descTowNumbers({firstNumber: this.descFirstNumber, secondNumber: this.descSecondNumber});
store.dispatch(action);
}
calculate = (type) => {
const calculateText = type === CountActionType.ADD ? '+' : '-';
const result = type === CountActionType.ADD ? this.state.addResult : this.state.descResult;
return (
<View style={{flexDirection: 'row'}}>
<TextInput style={styles.textInput} defaultValue={'0'} onChangeText = {this.firstTextChange(type)}/>
<Text> {calculateText} </Text>
<TextInput style={styles.textInput} defaultValue={'0'} onChangeText = {this.secondTextChange(type)}/>
<Text> = </Text>
<Text>{result}</Text>
</View>
);
}
render () {
return (
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
{this.calculate(CountActionType.ADD)}
{this.calculate(CountActionType.DESC)}
</View>
);
}
}