1. 程式人生 > >前端入坑,先入了React坑

前端入坑,先入了React坑

const Calculator = React.createClass({
    getInitialState: function() {
        return { expression: ''};
    },
    handleClick: function(value) {
        if(value=='=')
        {
          this.setState({expression:eval(this.state.expression)+''});
        }
        else if(value=='b')
        {
          this.setState({expression:this.state.expression.slice(0,-1)});
        }
        else if(value=='c')
        {
          this.setState({expression:''});
        }
        else
        {
            this.setState({expression:this.state.expression+=value});
        }
  },
  handleChange: function(value) {
    this.setState({expression:value});
  },
  render: function() {
    return <div style={{width:'215px'}}>
            <TextEdit onChange={this.handleChange} value={this.state.expression}/>
            <ButtonToolbar>
            <ButtonGroup bsSize="large">
            <SetButton num='1' onClick={this.handleClick}/>
            <SetButton num='2' onClick={this.handleClick}/>
            <SetButton num='3' onClick={this.handleClick}/>
            <SetButton num='/' onClick={this.handleClick}/>
            <SetButton num='(' onClick={this.handleClick}/>
            </ButtonGroup>
            </ButtonToolbar>

            <ButtonToolbar>
            <ButtonGroup bsSize="large">
            <SetButton num='4' onClick={this.handleClick}/>
            <SetButton num='5' onClick={this.handleClick}/>
            <SetButton num='6' onClick={this.handleClick}/>
            <SetButton num='*' onClick={this.handleClick}/>
            <SetButton num=')' onClick={this.handleClick}/>
            </ButtonGroup>
             </ButtonToolbar>

            <ButtonToolbar>
            <ButtonGroup bsSize="large">
            <SetButton num='7' onClick={this.handleClick}/>
            <SetButton num='8' onClick={this.handleClick}/>
            <SetButton num='9' onClick={this.handleClick}/>
            <SetButton num='-' onClick={this.handleClick}/>
            <SetButton num='b' onClick={this.handleClick}/>
            </ButtonGroup>
            </ButtonToolbar>

            <ButtonToolbar>
            <ButtonGroup bsSize="large">
            <SetButton num='0' onClick={this.handleClick}/>
            <SetButton num='.' onClick={this.handleClick}/>
            <SetButton num='=' onClick={this.handleClick}/>
            <SetButton num='+' onClick={this.handleClick}/>
            <SetButton num='c' onClick={this.handleClick}/>
            </ButtonGroup>
            </ButtonToolbar>
          </div>;
  }
});

以上程式碼實現裡一個簡單的計算器的功能。

不完整,前後補上

var React = require('react')
var ReactDOM = require('react-dom')
var ReactBootstrap = require('react-bootstrap')
var Button = ReactBootstrap.Button;
var ButtonGroup = ReactBootstrap.ButtonGroup;
var ButtonToolbar = ReactBootstrap.ButtonToolbar;
var FormControl = ReactBootstrap.FormControl;

export default Calculator;

這就是一個可用的計算器元件了。

使用的例子,把這個計算器放到id為info的div裡