Business needs to specifically look at the React Native Animate animation to make a Toast prompt box
// Toast
import React from 'react';
import { Animated, Text, View, Easing, Dimensions, Modal,StyleSheet } from 'react-native';
const widthScreen = Dimensions.get('window').width
exportDefault class Toast extends React.Component {state = {fadeAnim: new Animated.Value(0), //' '// Display text refToast:false// Whether to bind timer by ref:' '// timer callback:null, ShwoToast = (duration = 2000) => {Animated. Sequence ([Animated. Timing (// Animated over time) This.state. fadeAnim, // The variable values in the animation {easing: easing. Linear, toValue: 1, // The opacity finally changes to 1, i.e., completely opaque duration: Duration, // Let the animation last for a while}),]).start(); } show = (text, duration,callback) => {this.settiner (duration) this.setState({text, refToast:true}) enclosing state. FadeAnim. SetValue (0) / / have to perform every time a change is zero, To make the animation hide from 0 to 1 display this.shwotoast () // Execute the animation callback&&callback() // callback}setTiner = () => {
this.state.timer = setTimeout(() => {
this.setState({ refToast: false })
clearTimeout(this.state.timer)
}, 2000);
}
render() {
let { fadeAnim, refToast } = this.state
let { showToast, duration } = this.props
let { width, left } = styles.container
let text = refToast ? this.state.text : this.props.text
if(! RefToast && showToast) {/ / Boolean value judgment whether to show Toast this. State. FadeAnim. SetValue (0) / / have to perform every time a change is zero, Show this.show(text, duration) // Execute animation showToast =false// Change tofalse} // Check that the text content is too large and the width is too largeif (text && text.length > 14) {
width = 200
left = (widthScreen / 2) - 100
} else{ width = 140 left = (widthScreen / 2) - 70 } const opacity = fadeAnim.interpolate({ inputRange: [0, 0.5, 1], / / display outputRange: [0, 5, 0] / / hide});return (
<View>
<Modal
animationType="none"Transparent ={refToast} visible={refToast} > <Animated.View // Use special animatable View component style={{... styles.container, opacity: Opacity, // Specify opacity as animation variable value width, left }} > <View style={styles.bodyView}> <Text style={styles.bodyText}>{text}</Text> </View> </Animated.View> </Modal> </View> ); } } const styles = StyleSheet.create({ container: { position:'absolute',
bottom: 80,
backgroundColor: '#ddd',
borderRadius: 10,
height: 'auto',
padding: 15,
width: 140,
left: (widthScreen / 2) - 70,
zIndex: 9991,
},
bodyView: {},
bodyText: {
textAlign: 'center'}})Copy the code
1. We need to introduce the Toast file
// app.js
import ToastView from './src/components/toast/Index';
Copy the code
2. Register in the app.js component
// app.js
render() {
return (
<Provider store={store}>
<View style={styles.app}>
<ToastView ref="toast" />
<StackNavigator />
</View>
</Provider>
);
}
Copy the code
3. You need to define a global variable for global use
// app.js
global.Toast = ' '// Toast popupCopy the code
4. The binding of refs needs to be obtained after node rendering is completed
app.js
componentDidMount() {this.refs.toast = this.refs.toast // bind Toast nodes}Copy the code
5. Complete code, I have included redux and routing
// app.js
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, BackHandler, ToastAndroid, Dimensions } from 'react-native';
import StackNavigator from './src/router/StackNavigator';
import { Provider } from 'react-redux';
import store from './src/redux/store';
import ToastView from './src/components/toast/Index';
const screenWidth = Dimensions.get('window').width;
import PreventDoublePress from './src/utils/PreventDoublePress'// Disable warning console.disableYellowBox =true;
console.warn('YellowBox is disabled.'); // Clear all console warnings after packagingif(! __DEV__) { global.console = { info: () => { },log: () => { }, warn: () => { }, debug: () => { }, error: () => { } }; } // global global.logintoken =' '// Login token global.toast =' '// Toast popupexportdefault class App extends Component { constructor(props) { super(props); This. state = {lastBackPressed: 0}} // Listen for the physical button while the page is being createdcomponentWillMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.BackHandler); }} // Destroy the listener when the page is destroyedcomponentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress', this.BackHandler); }}componentDidMount() {Toast = this.refs.toast // Bind Toast node} // Physical return key event triggers BackHandler = () => {if (this.state.lastBackPressed && this.state.lastBackPressed + 2000 >= Date.now()) {
BackHandler.exitApp()
return false
}
this.state.lastBackPressed = Date.now()
ToastAndroid.show('Press exit app again', ToastAndroid.SHORT)
return true
}
render() {
return (
<Provider store={store}>
<View style={styles.app}>
<ToastView ref="toast" />
<StackNavigator />
</View>
</Provider>
);
}
}
const styles = StyleSheet.create({
app: {
flex: 1,
flexDirection: 'row'
},
toast: {
position: 'absolute',
bottom: 50,
left: screenWidth / 2,
backgroundColor: '#aaa',
width: 100,
height: 'auto',
zIndex: 999
},
toastText: {
// color:'# 000'}});Copy the code
How to use: Toast.show directly in any business page
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { getDate } from '.. /.. /.. /redux/actions'
import { connect } from 'react-redux';
import styles from './Style'Class Index extends Component {showtoast = () => {toast.show (' toast.show ')}render() {
return(<View style={styles.container}> <Text onPress={() => this.showtoast()}> Click to display the Toast box </Text> </View>); } } const mapStateToProps = state => ({ store: state.store })export default connect(mapStateToProps)(Index);
Copy the code
Toast.show() can be submitted with three parameters: 1: displayed text 2: displayed duration default 2000 ms 3: callback function
Toast.show('Toast content',2000,() => {// do something})Copy the code
The final result
It can also be referenced separately on the current page
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { getDate } from '.. /.. /.. /redux/actions'
import { connect } from 'react-redux';
import styles from './Style'
import Toast from '.. /.. /.. /components/toast/Index'Class Index extends Component {constructor(props) {super(props); this.state = { text:' ',
show:false
}
}
showtoast = () => {
this.setState({
text:'Toast display content ',
show:true})}render() {
return( <View style={styles.container}> <Toast text={this.state.text} show={this.state.show} /> <Text onPress={() => This.showtoast ()}> Click to show the Toast box </Text> </View>); } } const mapStateToProps = state => ({ store: state.store })export default connect(mapStateToProps)(Index);
Copy the code