Skip to content

Commit b85d910

Browse files
committed
Add method onPress so this app look like real Calculator in your app
1 parent 6d674c5 commit b85d910

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

App.js

+34-6
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,47 @@ import styles from './src/styles/_calculator'
55
class App extends React.Component {
66
constructor() {
77
super()
8+
this.state = {
9+
calculationText: ""
10+
}
11+
}
12+
13+
calculateResult() {
14+
const text = this.state.calculationText
15+
// now parse this text
16+
}
817

18+
buttonbPressed(text) {
19+
//console.log(text)
20+
21+
if(text == '=') {
22+
return this.calculateResult()
23+
}
24+
this.setState({
25+
calculationText: this.state.calculationText + text
26+
})
927
}
1028

11-
29+
operate(operation) {
30+
switch(operation) {
31+
case 'Del' :
32+
let text = this.state.calculationText.split('')
33+
text.pop()
34+
35+
this.setState({
36+
calculationText: text.join('')
37+
})
38+
}
39+
}
1240

1341
render() {
1442
let rows = [];
15-
let numb = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, '=']];
43+
let numb = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [".", 0, '=']];
1644
for(let i = 0; i < 4; i++) {
1745
let row = []
1846
for(let j = 0; j < 3; j++) {
1947
row.push(
20-
<TouchableOpacity style={styles.btn}>
48+
<TouchableOpacity onPress={() => this.buttonbPressed(numb[i][j])}>
2149
<Text style={styles.btnText}>{numb[i][j]}</Text>
2250
</TouchableOpacity>
2351
)
@@ -26,18 +54,18 @@ class App extends React.Component {
2654
}
2755

2856
let oper = [];
29-
let operation = ['+', '-', '*', '/'];
57+
let operation = ['Del', '+', '-', '*', '/'];
3058
for(let i = 0; i < 4; i++) {
3159
oper.push(
32-
<TouchableOpacity style={styles.btn}>
60+
<TouchableOpacity style={styles.btn} onPress={() => this.operate(operation[i])}>
3361
<Text style={[styles.btnText, {color: 'white'}]}>{operation[i]}</Text>
3462
</TouchableOpacity>
3563
)
3664
}
3765
return (
3866
<View style={styles.container}>
3967
<View style={styles.calculation}>
40-
<Text style={styles.calculationText}>11*11</Text>
68+
<Text style={styles.calculationText}>{this.state.calculationText}</Text>
4169
</View>
4270
<View style={styles.result}>
4371
<Text style={styles.resultText}>121</Text>

0 commit comments

Comments
 (0)