首頁  >  文章  >  web前端  >  ReactNative實作Toast的範例分享

ReactNative實作Toast的範例分享

小云云
小云云原創
2018-01-03 09:01:062030瀏覽

本文主要介紹了ReactNative實作Toast的範例,小編覺得還挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

對於Android開發工程師來說,Toast在熟悉不過了,用它來顯示一個提示訊息,並自動隱藏。在我們開發RN應用的時候,我門也要實現這樣的效果,就一點困難了,倒也不是困難,只是需要我們去適配,RN官方提供了一個API ToastAndroid,看到這個名字應該猜出,它只能在Android中使用,在iOS中使用沒有效果,所以,我們需要適配或我們自訂一個,今天的這篇文章就是自訂一個Toast使其在Android和iOS都能運行,並且有相同的運行效果。

源碼傳送門

定義元件


#
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

首先導入我們必須的基礎元件以及API,我們自訂元件都需要繼承它,Dimensions用於實現動畫,Easing用於設定動畫的軌跡運行效果,PropTypes用於對屬性類型進行定義。

render方法是我們定義元件渲染的入口,最外層view使用position為absolute,並設定left,right,top,bottom設定為0,使其佔滿螢幕,這樣使用Toast顯示期間不讓介面監聽點擊事件。內層View是Toast顯示的黑框容器,backgroundColor屬性設定rgba形式,顏色為黑色透明度為0.6。並設定圓角以及最大寬度為螢幕寬度的一半。然後就是Text元件用來顯示具體的提示訊息。

我們也看到propTypes用來限定屬性message的型別為string。 constructor是我們元件的建構方法,有一個props參數,此參數為傳遞過來的一些屬性。需要注意,建構方法中首先要呼叫super(props),否則報錯,在此處,我將傳遞來的值設定到了state。

對於Toast,顯示一會兒自動消失,我們可以透過setTimeout實現這個效果,在componentDidMount呼叫此方法,此處設定時間為1000ms。然後將隱藏毀掉揭露出去。當我們使用setTimeout時還需要在元件卸載時清除定時器。組件卸載時回呼的時componentWillUnmount。所以在此處清除定時器。

實現動畫效果

在上面我們實現了Toast的效果,但是顯示和隱藏都沒有過度動畫,略顯生硬。然後我們加一些平移和透明度的動畫,然後對componentDidMount修改實現動畫效果

在元件中增加兩個變數


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

在之前內層在view的樣式中,設定的bottom是height/8。我們此處將view樣式設定如下


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

然後修改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();
  }

也就是bottom顯示時從height /12到height/8移動,時間是80ms,透明度從0到1轉變執行時間100ms。在上面我們看到有個easing屬性,該屬性傳的是動畫執行的曲線速度,可以自己實現,在Easing API中已經有多種不同的效果。大家可以自己去看看實現,原始碼位址是https://github.com/facebook/react-native/blob/master/Libraries/Animated/src/Easing.js ,自己實現的話直接給一個運算函數就可以,可以自己去看模仿。

定義顯示時間

在前面我們設定Toast顯示1000ms,我們對顯示時間進行自訂,限定類型number,


time: PropTypes.number

在建構方法中對時間的處理


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

在此我對時間顯示處理為SHORT和LONG兩種值了,當然你可以自己處理為想要的效果。

然後只要修改timingDismiss中的時間1000,寫為this.state.time就可以了。

元件更新

當元件已經存在時再次更新屬性時,我們需要對此進行處理,更新state中的message和time,並清除計時器,重新定時。


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

元件註冊

#為了我們的定義的元件以API的形式調用,而不是寫在render方法中,所以我們定義一個跟元件


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

RootView就是我們定義的根元件,實作如上,透過AppRegistry.registerComponent註冊。

為外部呼叫


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

Toast中定義兩個static變數,表示顯示的時間供外部使用。然後提供兩個static方法,方法中呼叫RootView的setView方法將ToastView設定到根view。

使用

先匯入上面的Toast,然後透過下面方法呼叫


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

相關推薦:

使用toast元件實作提示使用者忘記輸入使用者名稱或密碼功能

#微信小程式自訂toast實作方法詳解

微信小程式之自訂toast實例詳解

#

以上是ReactNative實作Toast的範例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn