-
Notifications
You must be signed in to change notification settings - Fork 114
/
index.js
118 lines (97 loc) · 2.66 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import React from "react";
import { StyleSheet, Text, View } from "react-native";
export default class ReadMore extends React.Component {
state = {
measured: false,
shouldShowReadMore: false,
showAllText: false
};
async componentDidMount() {
this._isMounted = true;
await nextFrameAsync();
if (!this._isMounted) {
return;
}
// Get the height of the text with no restriction on number of lines
const fullHeight = await measureHeightAsync(this._text);
this.setState({ measured: true });
await nextFrameAsync();
if (!this._isMounted) {
return;
}
// Get the height of the text now that number of lines has been set
const limitedHeight = await measureHeightAsync(this._text);
if (fullHeight > limitedHeight) {
this.setState({ shouldShowReadMore: true }, () => {
this.props.onReady && this.props.onReady();
});
} else {
this.props.onReady && this.props.onReady();
}
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
let { measured, showAllText } = this.state;
let { numberOfLines } = this.props;
return (
<View>
<Text
numberOfLines={measured && !showAllText ? numberOfLines : 0}
style={this.props.textStyle}
ref={text => {
this._text = text;
}}
>
{this.props.children}
</Text>
{this._maybeRenderReadMore()}
</View>
);
}
_handlePressReadMore = () => {
this.setState({ showAllText: true });
};
_handlePressReadLess = () => {
this.setState({ showAllText: false });
};
_maybeRenderReadMore() {
let { shouldShowReadMore, showAllText } = this.state;
if (shouldShowReadMore && !showAllText) {
if (this.props.renderTruncatedFooter) {
return this.props.renderTruncatedFooter(this._handlePressReadMore);
}
return (
<Text style={styles.button} onPress={this._handlePressReadMore}>
Read more
</Text>
);
} else if (shouldShowReadMore && showAllText) {
if (this.props.renderRevealedFooter) {
return this.props.renderRevealedFooter(this._handlePressReadLess);
}
return (
<Text style={styles.button} onPress={this._handlePressReadLess}>
Hide
</Text>
);
}
}
}
function measureHeightAsync(component) {
return new Promise(resolve => {
component.measure((x, y, w, h) => {
resolve(h);
});
});
}
function nextFrameAsync() {
return new Promise(resolve => requestAnimationFrame(() => resolve()));
}
const styles = StyleSheet.create({
button: {
color: "#888",
marginTop: 5
}
});