-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.jsx
76 lines (62 loc) · 1.76 KB
/
calculator.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React from 'react';
class Calculator extends React.Component{
constructor(props){
super(props);
this.state = {num1: "", num2: "", result: 0}
this.setNum1 = this.setNum1.bind(this);
this.add = this.add.bind(this);
this.subtract = this.subtract.bind(this);
this.multiply = this.multiply.bind(this);
this.divide = this.divide.bind(this);
this.clear = this.clear.bind(this);
}
setNum1(e) {
const num1 = e.target.value ? parseInt(e.target.value) : "";
this.setState({ num1 });
}
setNum2(e) {
const num2 = e.target.value ? parseInt(e.target.value) : "";
this.setState({ num2 });
}
add(e) {
e.preventDefault();
const result = this.state.num1 + this.state.num2;
this.setState({ result });
}
subtract(e) {
e.preventDefault();
const result = this.state.num1 - this.state.num2;
this.setState({ result });
}
multiply(e) {
e.preventDefault();
const result = this.state.num1 * this.state.num2;
this.setState({ result });
}
divide(e) {
e.preventDefault();
const result = this.state.num1 / this.state.num2;
this.setState({ result });
}
clear(e) {
e.preventDefault();
this.setState({ num1: "", num2: "", result: 0 });
}
render() {
const {num1, num2, result} = this.state;
return (
<div>
<h1>{result}</h1>
<input onChange={this.setNum1} value={num1}/>
<input onChange={this.setNum2} value={num2}/>
<button onClick={this.clear}>Clear</button>
<br />
<button onClick={this.add}>+</button>
<button onClick={this.subtract}>-</button>
<button onClick={this.multiply}>*</button>
<button onClick={this.divide}>/</button>
</div>
);
}
}
export default Calculator;