Home > Web Front-end > JS Tutorial > body text

Example sharing of implementing Toast in ReactNative

小云云
Release: 2018-01-03 09:01:06
Original
2122 people have browsed it

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=&#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 the basic components we need and API, our custom components all need to inherit it, Dimensions is used to implement animation, Easing is used to set the trajectory running effect of animation, and PropTypes is used to define attribute 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 in 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 to the component


moveAnim = new Animated.Value(height / 12);
  opacityAnim = new Animated.Value(0);
Copy after login

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


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

and then modify componentDidMount

##

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 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
Copy after login

Handling of time in the constructor

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

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

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, So we define a follower component

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 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 &#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

Toast.show("测试,我是Toast");
          //能设置显示时间的Toast
          Toast.show("测试",Toast.LONG);
Copy after login

Related recommendations:

Use the toast component to realize the function of prompting the user to forget to enter the user name or password

Detailed 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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template