Created
November 1, 2017 08:16
-
-
Save pyldin601/e014156a0e516591109d5f2342505648 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
interface BlurTextInputStateInterface { | |
value: string, | |
lastChangeEvent: React.ChangeEvent<HTMLInputElement>, | |
} | |
export default class extends React.Component<React.InputHTMLAttributes<HTMLInputElement>, BlurTextInputStateInterface> { | |
constructor(props: any) { | |
super(props); | |
this.state = { | |
value: props.value, | |
lastChangeEvent: null, | |
}; | |
this.onChange = this.onChange.bind(this); | |
this.onBlur = this.onBlur.bind(this); | |
} | |
public componentWillReceiveProps(nextProps) { | |
if (nextProps.value === this.props.value) { | |
return; | |
} | |
this.setState({ | |
value: nextProps.value, | |
lastChangeEvent: null, | |
}) | |
} | |
public onBlur() { | |
if (this.state.lastChangeEvent) { | |
this.props.onChange(this.state.lastChangeEvent); | |
} | |
} | |
public onChange(event: React.ChangeEvent<HTMLInputElement>) { | |
event.persist(); | |
this.setState({ | |
value: event.currentTarget.value, | |
lastChangeEvent: event, | |
}); | |
} | |
public render() { | |
return <input | |
{...this.props} | |
onBlur={this.onBlur} | |
onChange={this.onChange} | |
value={this.state.value} | |
/> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment