Advertisement
Guest User

Untitled

a guest
Dec 14th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import React from 'react';
  2.  
  3.  
  4. class Product extends React.Component {
  5. constructor(props) {
  6. super(props);
  7.  
  8. this.state = {
  9. quantity: {
  10. value: 0,
  11. displayValue: '0',
  12. prevValue: 0
  13. }
  14. };
  15.  
  16. this.setQuantity = this.setQuantity.bind(this);
  17. this.onLoseFocus = this.onLoseFocus.bind(this);
  18. this.updateQuantity = this.updateQuantity.bind(this);
  19. }
  20.  
  21. setQuantity(e) {
  22. this.updateQuantity(e.target.value);
  23. }
  24.  
  25. onLoseFocus() {
  26. let { quantity } = this.state;
  27. const currentValue = quantity.displayValue || quantity.prevValue
  28.  
  29. quantity = {
  30. ...quantity,
  31. displayValue: currentValue,
  32. prevValue: currentValue
  33. }
  34.  
  35. this.setState(prev => ({ ...prev, quantity}));
  36. }
  37.  
  38. updateQuantity(displayValue) {
  39. const { value, prevValue } = this.state.quantity;
  40. const newValue = displayValue === '' ? value : Number(displayValue)
  41.  
  42. if (Number.isInteger(newValue)) {
  43. const quantity = {
  44. ...this.state.quantity,
  45. value: newValue,
  46. displayValue
  47. };
  48.  
  49. this.setState(prev => ({ ...prev, quantity}));
  50. }
  51. }
  52.  
  53.  
  54. render() {
  55. const { displayValue } = this.state.quantity;
  56. return (
  57. <div>
  58. <input type="text" value={displayValue} onChange={this.setQuantity} onBlur={this.onLoseFocus} />
  59. </div>
  60. )
  61. }
  62. }
  63.  
  64. export default Product;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement