So they’re going to make a calculator, and they’re going to do basic things like add, subtract, multiply, and divide, and they’re going to hit =, and they’re going to hit AC.

The difficulty at first was putting the numbers together. For example, if you click 4, then 9, you get 49. After thinking about it, I decided to use the string combination method:

Click 4, then click 9, and then click the + sign. If you spell the string, it will be “49+”.

The difficulty is to determine the object to be pieced together. Use React to get the text content of DOM element nodes. I took a long time to find the innerText with e.target.innertext.

And then, finally, how to turn a string operation into a mathematical operation, and it took me a long time to realize that you can use eval to evaluate a mathematical formula in a string.

There are basically no difficulties.

class Caculator extends React.Component{ constructor(props){ super(props) this.state = { text:"" } this.change = this.change.bind(this) this.cal = this.cal.bind(this) this.cl = this.cl.bind(this) } change(e){ this.setState({ text:this.state.text + e.target.innerText }) } cal(){ this.setState({ text: eval(this.state.text) }) } cl(){ this.setState({ text:"" }) } render(){ return( <div id="caculator"> <div id="display"> {this.state.text} </div> <div id="number"> <div id="one" onClick={this.change}> 1 </div> <div id="two" onClick={this.change}> 2 </div> <div id="three" onClick={this.change}> 3 </div> <div id="four" onClick={this.change}> 4 </div> <div id="five" onClick={this.change}> 5 </div> <div id="six" onClick={this.change}> 6 </div> <div id="seven" onClick={this.change}> 7 </div> <div id="eight" onClick={this.change}> 8 </div> <div id="night" onClick={this.change}> 9  </div> <div id="zero" onClick={this.change}> 0 </div> <div id="decimal" onClick={this.change}> . </div> <div id="add" onClick={this.change}> + </div> <div id="substract" onClick={this.change}> - </div> <div id="multiply" onClick={this.change}> * </div> <div id="divide" onClick={this.change}> / </div> <div id="equals" onClick={this.cal}> = </div> <div id="clear" onClick={this.cl}> AC </div> </div> </div> ) } } ReactDOM.render( <Caculator/>, document.getElementById('root') );Copy the code

Click here to see the CodePen demo.