Home Web Front-end JS Tutorial How to implement Toast using ReactNative

How to implement Toast using ReactNative

Jun 14, 2018 pm 03:15 PM
toast

This article mainly introduces the example of implementing Toast in ReactNative. Now I share it with you and give it as a reference.

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

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

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=&#39;none&#39;>

        <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: &#39;rgba(0,0,0,.6)&#39;,

    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

Copy after login

First import our necessary basic components and API, our custom components need to inherit it, Dimensions Used to implement animation, Easing is used to set the trajectory running effect of animation, and PropTypes is used to define property types.

The render method is the entrance for us to define component rendering. The outermost view uses position as absolute, and sets left, right, top, and bottom to 0 so that it fills the screen. In this way, it will not be displayed during Toast display. Let the interface listen for click events. The inner View is a black frame container displayed by Toast. The backgroundColor attribute is set to rgba format, and the color is black and the transparency is 0.6. And set rounded corners and max-width to half the screen width. Then the Text component is used to display specific prompt information.

We also see that propTypes is used to limit the type of attribute message to string. The constructor is the construction method of our component. It has a props parameter, which is some properties passed over. It should be noted that super(props) must be called first in the constructor, otherwise an error will be reported. Here, I set the passed value into the state.

For Toast, the display will disappear automatically after a while. We can achieve this effect through setTimeout. Call this method on componentDidMount. The time here is set to 1000ms. Then the hidden destruction is exposed. When we use setTimeout, we also need to clear the timer when the component is unloaded. componentWillUnmount is called back when the component is unmounted. So clear the timer here.

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 effects

Add two variables in the component

1

2

moveAnim = new Animated.Value(height / 12);

  opacityAnim = new Animated.Value(0);

Copy after login

In the previous style of the inner view, the bottom set is height/8. Here we set the view style as follows

1

style={[styles.textContainer, {bottom: this.moveAnim, opacity: this.opacityAnim}]}

Copy after login

and then modify componentDidMount

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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();

  }

Copy after login

That is, when the bottom is displayed, it moves from height/12 to height/8, the time is 80ms, and the transparency changes from 0 to 1 Execution time 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 yourself.

Define the display time

In the front we set the Toast display to 1000ms, we customize the display time, and limit the type number,

1

time: PropTypes.number

Copy after login

In the construction The processing of time in the method

1

time: props.time && props.time < 1500 ? Toast.SHORT : Toast.LONG,

Copy after login

Here I have processed the time display into two values, SHORT and LONG. Of course, you can process it yourself to the desired effect.

Then you only need to modify the time 1000 in timingDismiss and write it as this.state.time.

Component update

When 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.

1

2

3

4

5

6

7

8

componentWillReceiveProps(nextProps) {

   this.setState({

      message: nextProps.message !== undefined ? nextProps.message : &#39;&#39;,

      time: nextProps.time && nextProps.time < 1500 ? Toast.SHORT : Toast.LONG,

    })

    clearTimeout(this.dismissHandler)

    this.timingDismiss()

  }

Copy after login

Component registration

In order for our defined components to be called in the form of API instead of written in the render method, we define a follow component

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

import React, {Component} from "react";

import {StyleSheet, AppRegistry, View, Text} from &#39;react-native&#39;;

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: &#39;relative&#39;,

  },

  rootView: {

    position: "absolute",

    left: 0,

    right: 0,

    top: 0,

    bottom: 0,

    flexDirection: "row",

    justifyContent: "center",

  }

});

export default RootView

Copy after login

RootView is the root component we defined. It is implemented as above and registered through AppRegistry.registerComponent.

Packaging for external calls

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

import React, {

  Component,

} from &#39;react&#39;;

import RootView from &#39;../RootView&#39;

import ToastView from &#39;./ToastView&#39;

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

Copy after login

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

1

2

3

Toast.show("测试,我是Toast");

          //能设置显示时间的Toast

          Toast.show("测试",Toast.LONG);

Copy after login

The above is what I compiled for everyone, I hope it will be helpful to everyone in the future helpful.

Related articles:

Use webpack to build vue scaffolding

How to use webpack to package files

Detailed introduction to building webpack

The above is the detailed content of How to implement Toast using ReactNative. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

From Websites to Apps: The Diverse Applications of JavaScript From Websites to Apps: The Diverse Applications of JavaScript Apr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

See all articles