Example sharing of implementing Toast in ReactNative
This article mainly introduces the example of ReactNative implementing Toast. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
For Android development engineers, Toast is very familiar. It is used to display a prompt message and automatically hide it. When we develop RN applications, it is a bit difficult for us to achieve such an effect, but it is not difficult at all. It just requires us to adapt. RN officially provides an API ToastAndroid. You should guess it when you see the name. It can only be used in Android, and has no effect when used in iOS. Therefore, we need to adapt or customize one. Today’s article is to customize a Toast so that it can run on both Android and iOS, and has the same operating effect.
Source code portal
Define components
##
import React, {Component} from 'react'; import { StyleSheet, View, Easing, Dimensions, Text, Animated } from 'react-native'; import PropTypes from 'prop-types'; import Toast from "./index"; const {width, height} = Dimensions.get("window"); const viewHeight = 35; class ToastView extends Component { static propTypes = { message:PropTypes.string, }; dismissHandler = null; constructor(props) { super(props); this.state = { message: props.message !== undefined ? props.message : '' } } render() { return ( <View style={styles.container} pointerEvents='none'> <Animated.View style={[styles.textContainer]}><Text style={styles.defaultText}>{this.state.message}</Text></Animated.View> </View> ) } componentDidMount() { this.timingDismiss() } componentWillUnmount() { clearTimeout(this.dismissHandler) } timingDismiss = () => { this.dismissHandler = setTimeout(() => { this.onDismiss() }, 1000) }; onDismiss = () => { if (this.props.onDismiss) { this.props.onDismiss() } } } const styles = StyleSheet.create({ textContainer: { backgroundColor: 'rgba(0,0,0,.6)', borderRadius: 8, padding: 10, bottom:height/8, maxWidth: width / 2, alignSelf: "flex-end", }, defaultText: { color: "#FFF", fontSize: 15, }, container: { position: "absolute", left: 0, right: 0, top: 0, bottom: 0, flexDirection: "row", justifyContent: "center", } }); export default ToastView
Achieve animation effect
We have implemented the Toast effect above, but the display and hiding are not overly animated, which is slightly stiff. Then we add some translation and transparency animations, and then modify componentDidMount to achieve animation effectsAdd two variables to the componentmoveAnim = new Animated.Value(height / 12); opacityAnim = new Animated.Value(0);
style={[styles.textContainer, {bottom: this.moveAnim, opacity: this.opacityAnim}]}
##
componentDidMount() { Animated.timing( this.moveAnim, { toValue: height / 8, duration: 80, easing: Easing.ease }, ).start(this.timingDismiss); Animated.timing( this.opacityAnim, { toValue: 1, duration: 100, easing: Easing.linear }, ).start(); }
That is, when bottom is displayed from height /12 to height/8 moves, the time is 80ms, the transparency transition from 0 to 1 takes 100ms. Above we see that there is an easing attribute, which passes the curve speed of animation execution. You can implement it yourself. There are many different effects in the Easing API. You can check out the implementation yourself. The source code address is https://github.com/facebook/react-native/blob/master/Libraries/Animated/src/Easing.js. If you want to implement it yourself, just give it a calculation function. You can watch and imitate it yourself. Define the display time
In the previous step, we set the Toast display to 1000ms. We customize the display time and limit the type to number,
time: PropTypes.number
Handling of time in the constructor
time: props.time && props.time < 1500 ? Toast.SHORT : Toast.LONG,
Here I display the time as SHORT and LONG. Of course, you You can process it yourself to get the desired effect.
Then you only need to modify the time 1000 in timingDismiss and write it as this.state.time.
Component updateWhen updating properties again when the component already exists, we need to process this, update the message and time in the state, and clear the timer, Retime.
componentWillReceiveProps(nextProps) { this.setState({ message: nextProps.message !== undefined ? nextProps.message : '', time: nextProps.time && nextProps.time < 1500 ? Toast.SHORT : Toast.LONG, }) clearTimeout(this.dismissHandler) this.timingDismiss() }
Component registration
In order for our defined components to be called in the form of API instead of written in the render method, So we define a follower component
import React, {Component} from "react"; import {StyleSheet, AppRegistry, View, Text} from 'react-native'; viewRoot = null; class RootView extends Component { constructor(props) { super(props); console.log("constructor:setToast") viewRoot = this; this.state = { view: null, } } render() { console.log("RootView"); return (<View style={styles.rootView} pointerEvents="box-none"> {this.state.view} </View>) } static setView = (view) => { //此处不能使用this.setState viewRoot.setState({view: view}) }; } const originRegister = AppRegistry.registerComponent; AppRegistry.registerComponent = (appKey, component) => { return originRegister(appKey, function () { const OriginAppComponent = component(); return class extends Component { render() { return ( <View style={styles.container}> <OriginAppComponent/> <RootView/> </View> ); }; }; }); }; const styles = StyleSheet.create({ container: { flex: 1, position: 'relative', }, rootView: { position: "absolute", left: 0, right: 0, top: 0, bottom: 0, flexDirection: "row", justifyContent: "center", } }); export default RootView
RootView which is the root component we defined. The implementation is as above and is registered through AppRegistry.registerComponent. Packaging for external calls
import React, { Component, } from 'react'; import RootView from '../RootView' import ToastView from './ToastView' class Toast { static LONG = 2000; static SHORT = 1000; static show(msg) { RootView.setView(<ToastView message={msg} onDismiss={() => { RootView.setView() }}/>) } static show(msg, time) { RootView.setView(<ToastView message={msg} time={time} onDismiss={() => { RootView.setView() }}/>) } } export default Toast
Two static variables are defined in Toast, indicating that the displayed time is for external use. Then provide two static methods, in which the setView method of RootView is called to set the ToastView to the root view. Use
First import the above Toast, and then call it through the following method
Toast.show("测试,我是Toast"); //能设置显示时间的Toast Toast.show("测试",Toast.LONG);
Related recommendations: Use the toast component to realize the function of prompting the user to forget to enter the user name or passwordDetailed explanation of the custom toast implementation method of the WeChat applet
Detailed explanation of custom toast instances of WeChat applet
The above is the detailed content of Example sharing of implementing Toast in ReactNative. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.

Recently, Baidu Netdisk Android client has ushered in a new version 8.0.0. This version not only brings many changes, but also adds many practical functions. Among them, the most eye-catching is the enhancement of the folder sharing function. Now, users can easily invite friends to join and share important files in work and life, achieving more convenient collaboration and sharing. So how do you share the files you need to share with your friends? Below, the editor of this site will give you a detailed introduction. I hope it can help you! 1) Open Baidu Cloud APP, first click to select the relevant folder on the homepage, and then click the [...] icon in the upper right corner of the interface; (as shown below) 2) Then click [+] in the "Shared Members" column 】, and finally check all

Do you have the latest activation key for win7 enterprise edition? If you install the official win7 enterprise version, you will be prompted to activate it with the windows7 enterprise product key, otherwise it will not work properly. So the editor will share with you some win7 enterprise version activation passwords, let's take a look. Q3VMJ-TMJ3M-99RF9-CVPJ3-Q7VF3KGMPT-GQ6XF-DM3VM-HW6PR-DX9G8MT39G-9HYXX-J3V3Q-RPXJB-RQ6D79JBBV-7Q7P7-CTDB7-KYBKG-X8HHCP72QK-2Y3B8-YDHDV-29DQB-QKWWM6 JQ

Mango TV has various types of movies, TV series, variety shows and other resources, and users can freely choose to watch them. Mango TV members can not only watch all VIP dramas, but also set the highest definition picture quality to help users watch dramas happily. Below, the editor will bring you some free Mango TV membership accounts for users to use, hurry up and take a look Take a look. Mango TV latest member account free sharing 2023: Note: These are the latest member accounts collected, you can log in directly and use them, do not change the password at will. Account number: 13842025699 Password: qds373 Account number: 15804882888 Password: evr6982 Account number: 13330925667 Password: jgqae Account number: 1703

Title: To solve the problem that Discuz WeChat shares cannot be displayed, specific code examples are needed. With the development of the mobile Internet, WeChat has become an indispensable part of people's daily lives. In website development, in order to improve user experience and expand website exposure, many websites will integrate WeChat sharing functions, allowing users to easily share website content to Moments or WeChat groups. However, sometimes when using open source forum systems such as Discuz, you will encounter the problem that WeChat shares cannot be displayed, which brings certain difficulties to the user experience.

How to share wifi hotspot in win7 system? After our computer is connected to the network, it can also share the wireless network. Many users want to share their computer's network to their mobile phones for use. Many friends don’t know how to operate in detail. The editor below has compiled the steps on how to share wifi hotspots in win7 system. If you are interested, follow the editor and read on! Steps on how to share wifi hotspot in win7 system 1. In order to turn on wifi hotspot, you must first have a wireless network card. The laptop comes with it. If you have a PC, you can buy a portable wifi to share wifi, which will not be described here. First press the windows key on the keyboard to open the start menu

People in the workplace will be familiar with PPT production, because whether it is a year-end summary or a work report, many companies require it to be presented in the form of PPT. At this time, I encountered a problem, that is, how to share PPT? Don’t worry, the editor below will show you how to share PPT. 1. First select the edited PPT and click Save in the upper left corner (if you are using WPS, you can click Login first). 2. Then click the share icon in the menu bar as shown below. 3. Then the sharing interface as shown below will pop up. You can see that a sharing link will appear. Click to send the link to share. 4. You can also click "Allow friends to edit" in the lower left corner of the picture below, so that friends can also click to edit this PPT. 5. If necessary, give P
