cuz
Version:
Front-end modular development kit.
118 lines (105 loc) • 2.69 kB
JavaScript
import React from 'react';
import Button from '../Button';
import Input from '../Input';
const NumberInput = React.createClass({
propTypes: {
value: React.PropTypes.number,
max: React.PropTypes.number,
min: React.PropTypes.number,
step: React.PropTypes.number,
disabled: React.PropTypes.bool,
},
getDefaultProps() {
return {
value: 0,
max: Number.POSITIVE_INFINITY,
min: Number.NEGATIVE_INFINITY,
step: 1,
disabled: false
};
},
getInitialState() {
const value = +this.props.value;
return {
value: value,
plusDisabled: this.props.disabled || value >= this.props.max,
minusDisabled: this.props.disabled || value <= this.props.min,
step: this.props.step,
};
},
validationState() {
if (isNaN(this.state.value) || this.state.value > +this.props.max || this.state.value < +this.props.min) return 'error';
},
handleChange() {
const value = +this.refs.input.getValue();
const state = {
value: value,
plusDisabled: (value >= +this.props.max),
minusDisabled: (value <= +this.props.min)
};
this.setState(state);
},
plusNumber() {
const value = this.state.value + +this.props.step;
const max = +this.props.max;
if (value >= max) {
this.setState({
value: max,
plusDisabled: true
});
return;
}
this.setState({
value: value,
minusDisabled: false
});
},
minusNumber() {
const value = this.state.value - +this.props.step;
const min = +this.props.min;
if (value <= min) {
this.setState({
value: min,
minusDisabled: true
});
return;
}
this.setState({
value: value,
plusDisabled: false
});
},
renderPlusButton() {
return (
<Button bsSize="small" onClick={this.plusNumber} disabled={this.state.plusDisabled} >
<i className="fa fa-plus"></i>
</Button>
);
},
renderMinusButton() {
return (
<Button bsSize="small" onClick={this.minusNumber} disabled={this.state.minusDisabled} >
<i className="fa fa-minus"></i>
</Button>
);
},
render() {
return (
<div className="number-input">
<Input
ref="input"
bsSize="small"
type="text"
value={this.state.value}
bsStyle={this.validationState()}
onChange = {this.handleChange}
buttonBefore={this.renderMinusButton()}
buttonAfter={this.renderPlusButton()}
disabled={this.props.disabled}
wrapperClassName="form-inline"
/>
</div>
);
}
});
export default NumberInput;