-
Notifications
You must be signed in to change notification settings - Fork 13
/
AutotypingText.js
99 lines (87 loc) · 1.94 KB
/
AutotypingText.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import HiddenText from './HiddenText';
import PropTypes from 'prop-types';
export default class AutotypingText extends Component {
static defaultProps = {
text: '',
charMovingTime: '50',
delay: 0,
style: {
color: 'black',
fontSize: 14
},
};
static propTypes = {
text: PropTypes.string.isRequired,
charMovingTime: PropTypes.number.isRequired,
style: PropTypes.object,
onComplete: PropTypes.func,
delay: PropTypes.number,
};
typingIntervalId = 0;
delayTimeoutId = 0;
constructor(props){
super(props);
this.state = {
textShow: '',
};
}
componentWillUnmount() {
clearInterval(this.typingIntervalId);
clearTimeout(this.delayTimeoutId);
}
_onResult = (text) => {
const { delay } = this.props;
clearTimeout(this.delayTimeoutId);
this.delayTimeoutId = setTimeout(() => {
this.startTyping(text);
}, delay);
};
startTyping(text) {
const {charMovingTime, onComplete} = this.props;
if(text === '') {
return;
}
let textShow = '';
let counter = 0;
let len = text.length;
clearInterval(this.typingIntervalId);
this.typingIntervalId = setInterval(
() => {
textShow += text[counter];
this.setState({textShow: textShow});
counter++;
if(counter >= len) {
clearInterval(this.typingIntervalId);
if(onComplete) {
onComplete();
}
}
}, parseInt(charMovingTime)
);
}
render() {
let textShow = this.state.textShow;
return (
<View style={[styles.flex1]}>
<Text { ...this.props }>
{textShow}
</Text>
<HiddenText
{ ...this.props }
onResult={this._onResult}
/>
</View>
);
}
}
const styles = StyleSheet.create({
flex1: {
flex: 1,
}
});