Last active
March 3, 2019 18:56
-
-
Save quarrant/41328d2d210690e7438c1d46520b02eb 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
interface Props { | |
text: string | undefined; | |
lines: number; | |
onCollapse?: () => void; | |
showMoreButton?: boolean; | |
isActive?: boolean; | |
} | |
const FONT_SIZE = 13; | |
export default class CollapseText extends React.PureComponent<Props> { | |
private realLines: number | null = null; | |
state = { | |
isCalculated: false, | |
canRecalculate: false, | |
showMoreButton: false, | |
}; | |
changeVisibilityMoreButton = () => { | |
const { lines, showMoreButton } = this.props; | |
const { canRecalculate } = this.state; | |
if (this.realLines && !canRecalculate) { | |
this.setState({ | |
isCalculated: true, | |
showMoreButton: showMoreButton && this.realLines > lines, | |
}); | |
} | |
}; | |
handleTextOnLayout = (event: LayoutEvent) => { | |
const { height } = event.nativeEvent.layout; | |
if (!this.realLines) { | |
this.realLines = Math.floor(height / FONT_SIZE); | |
} | |
this.changeVisibilityMoreButton(); | |
}; | |
handleOnCollapse = () => { | |
const { onCollapse } = this.props; | |
this.setState( | |
{ | |
isCalculated: false, | |
canRecalculate: true, | |
showMoreButton: false, | |
}, | |
onCollapse, | |
); | |
}; | |
renderMoreButton = () => { | |
const { showMoreButton } = this.state; | |
if (showMoreButton) { | |
return ( | |
<ShadowContainer onPress={this.handleOnCollapse} activeOpacity={0.8}> | |
<MoreButtonContainer> | |
<MoreButtonText>ещё</MoreButtonText> | |
</MoreButtonContainer> | |
</ShadowContainer> | |
); | |
} | |
}; | |
render() { | |
const { text, lines, isActive } = this.props; | |
const { isCalculated } = this.state; | |
let textProps = {}; | |
if (isCalculated) { | |
textProps = { numberOfLines: lines }; | |
} | |
return ( | |
<View> | |
<Text {...textProps} isActive={isActive} onLayout={this.handleTextOnLayout}> | |
{text} | |
</Text> | |
{this.renderMoreButton()} | |
</View> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment