Guest User

Untitled

a guest
Apr 24th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. interface Props {
  2. value: number;
  3. onChange: (value: number) => void;
  4. widthPx?: number;
  5. inline?: boolean;
  6. disabled?: boolean;
  7. }
  8.  
  9. interface State {
  10. valueAsString: string;
  11. }
  12.  
  13. export class InputNumber extends React.Component<Props, State> {
  14. constructor(props: Props) {
  15. super(props);
  16. this.state = { valueAsString: isEmpty(props.value) ? '' : props.value.toString() };
  17. }
  18.  
  19. handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  20. const valueAsString = e.target.value;
  21. const valueAsNumber = toFloat(valueAsString);
  22. this.setState({ valueAsString: valueAsString }, () => {
  23. this.props.onChange(valueAsNumber);
  24. });
  25.  
  26. }
  27. componentWillReceiveProps(nextProps: Props) {
  28. if (nextProps.value !== toFloat(this.state.valueAsString)) {
  29. this.setState({ valueAsString: isEmpty(nextProps.value) ? '' : nextProps.value.toString() });
  30. }
  31. }
  32. render() {
  33. const { widthPx, inline, disabled } = this.props;
  34. const style: React.CSSProperties = { width: widthPx || '100%', display: inline ? 'inline-block' : 'block' };
  35. return (<div style={style}>
  36. <input type="text" value={this.state.valueAsString} onChange={this.handleChange} style={style} disabled={disabled} />
  37. </div>);
  38. }
  39. }
  40.  
  41. function isEmpty(val: number): boolean {
  42. const t = typeof val;
  43. return t === 'undefined' || val === null || (t === 'number' && isNaN(val));
  44. }
  45.  
  46. function toFloat(s: string) {
  47. return parseFloat(s.replace(/,/g, ''));
  48. }
Add Comment
Please, Sign In to add comment