|
| 1 | +import React,{ |
| 2 | + Component, |
| 3 | + PropTypes, |
| 4 | + View, |
| 5 | + StyleSheet, |
| 6 | + Text, |
| 7 | + Dimensions, |
| 8 | + Animated |
| 9 | +} from 'react-native'; |
| 10 | + |
| 11 | +const { height, width } = Dimensions.get('window'); |
| 12 | +const toastWidth = width * 0.7; |
| 13 | +const defaultText = 'Toast'; |
| 14 | +const defaultTimeout = 2000; |
| 15 | + |
| 16 | + |
| 17 | +class Toast extends Component { |
| 18 | + static propTypes = { |
| 19 | + duration: PropTypes.number |
| 20 | + }; |
| 21 | + |
| 22 | + |
| 23 | + static defaultProps = { |
| 24 | + duration: 300 |
| 25 | + }; |
| 26 | + |
| 27 | + |
| 28 | + constructor(props) { |
| 29 | + super(props); |
| 30 | + this.state = { |
| 31 | + fadeAnim: new Animated.Value(0.4), |
| 32 | + show: false, |
| 33 | + text: defaultText, |
| 34 | + timeout: defaultTimeout |
| 35 | + }; |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + componentWillUnmount() { |
| 40 | + clearTimeout(this.timeout); |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + show(text = defaultText, timeout = defaultTimeout) { |
| 45 | + const { duration } = this.props; |
| 46 | + Animated.timing(this.state.fadeAnim, { |
| 47 | + toValue: 1, |
| 48 | + duration: duration |
| 49 | + }).start(); |
| 50 | + |
| 51 | + this.setState({ |
| 52 | + show: true, |
| 53 | + text, |
| 54 | + timeout |
| 55 | + }); |
| 56 | + |
| 57 | + this.timeout = setTimeout(()=> { |
| 58 | + Animated.timing(this.state.fadeAnim, { |
| 59 | + toValue: 0, |
| 60 | + duration: duration |
| 61 | + }).start(()=> { |
| 62 | + this.setState({ |
| 63 | + show: false |
| 64 | + }); |
| 65 | + }); |
| 66 | + }, timeout - duration); |
| 67 | + } |
| 68 | + |
| 69 | + |
| 70 | + render() { |
| 71 | + const opacity = { |
| 72 | + opacity: this.state.fadeAnim |
| 73 | + }; |
| 74 | + if (!this.state.show) return null; |
| 75 | + return ( |
| 76 | + <Animated.View style={[styles.container, this.props.style, opacity]}> |
| 77 | + <Text style={styles.text}> |
| 78 | + {this.state.text} |
| 79 | + </Text> |
| 80 | + </Animated.View> |
| 81 | + ) |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +const styles = StyleSheet.create({ |
| 86 | + container: { |
| 87 | + position: 'absolute', |
| 88 | + backgroundColor: 'rgba(0,0,0,0.8)', |
| 89 | + borderRadius: 5, |
| 90 | + flexDirection: 'row', |
| 91 | + justifyContent: 'center', |
| 92 | + alignItems: 'center', |
| 93 | + width: toastWidth, |
| 94 | + left: (width - toastWidth) / 2, |
| 95 | + top: (height - 60) / 2, |
| 96 | + padding: 20 |
| 97 | + }, |
| 98 | + text: { |
| 99 | + flex: 1, |
| 100 | + color: 'white', |
| 101 | + fontSize: 16, |
| 102 | + textAlign: 'center' |
| 103 | + } |
| 104 | +}); |
| 105 | + |
| 106 | + |
| 107 | +export default Toast; |
0 commit comments