Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- class Product extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- quantity: {
- value: 0,
- displayValue: '0',
- prevValue: 0
- }
- };
- this.setQuantity = this.setQuantity.bind(this);
- this.onLoseFocus = this.onLoseFocus.bind(this);
- this.updateQuantity = this.updateQuantity.bind(this);
- }
- setQuantity(e) {
- this.updateQuantity(e.target.value);
- }
- onLoseFocus() {
- let { quantity } = this.state;
- const currentValue = quantity.displayValue || quantity.prevValue
- quantity = {
- ...quantity,
- displayValue: currentValue,
- prevValue: currentValue
- }
- this.setState(prev => ({ ...prev, quantity}));
- }
- updateQuantity(displayValue) {
- const { value, prevValue } = this.state.quantity;
- const newValue = displayValue === '' ? value : Number(displayValue)
- if (Number.isInteger(newValue)) {
- const quantity = {
- ...this.state.quantity,
- value: newValue,
- displayValue
- };
- this.setState(prev => ({ ...prev, quantity}));
- }
- }
- render() {
- const { displayValue } = this.state.quantity;
- return (
- <div>
- <input type="text" value={displayValue} onChange={this.setQuantity} onBlur={this.onLoseFocus} />
- </div>
- )
- }
- }
- export default Product;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement