Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface Props {
- value: number;
- onChange: (value: number) => void;
- widthPx?: number;
- inline?: boolean;
- disabled?: boolean;
- }
- interface State {
- valueAsString: string;
- }
- export class InputNumber extends React.Component<Props, State> {
- constructor(props: Props) {
- super(props);
- this.state = { valueAsString: isEmpty(props.value) ? '' : props.value.toString() };
- }
- handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const valueAsString = e.target.value;
- const valueAsNumber = toFloat(valueAsString);
- this.setState({ valueAsString: valueAsString }, () => {
- this.props.onChange(valueAsNumber);
- });
- }
- componentWillReceiveProps(nextProps: Props) {
- if (nextProps.value !== toFloat(this.state.valueAsString)) {
- this.setState({ valueAsString: isEmpty(nextProps.value) ? '' : nextProps.value.toString() });
- }
- }
- render() {
- const { widthPx, inline, disabled } = this.props;
- const style: React.CSSProperties = { width: widthPx || '100%', display: inline ? 'inline-block' : 'block' };
- return (<div style={style}>
- <input type="text" value={this.state.valueAsString} onChange={this.handleChange} style={style} disabled={disabled} />
- </div>);
- }
- }
- function isEmpty(val: number): boolean {
- const t = typeof val;
- return t === 'undefined' || val === null || (t === 'number' && isNaN(val));
- }
- function toFloat(s: string) {
- return parseFloat(s.replace(/,/g, ''));
- }
Add Comment
Please, Sign In to add comment