欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ReactNative實現(xiàn)Toast的示例

 更新時間:2017年12月31日 10:17:29   作者:Code4Android  
這篇文章主要介紹了ReactNative實現(xiàn)Toast的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

對于Android開發(fā)工程師來說,Toast在熟悉不過了,用它來顯示一個提示信息,并自動隱藏。在我們開發(fā)RN應用的時候,我門也要實現(xiàn)這樣的效果,就一點困難了,倒也不是困難,只是需要我們去適配,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='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

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

render方法是我們定義組件渲染的入口,最外層view使用position為absolute,并設置left,right,top,bottom設置為0,使其占滿屏幕,這樣使用Toast顯示期間不讓界面監(jiān)聽點擊事件。內層View是Toast顯示的黑框容器,backgroundColor屬性設置rgba形式,顏色為黑色透明度為0.6。并設置圓角以及最大寬度為屏幕寬度的一半。然后就是Text組件用于顯示具體的提示信息。

我們還看到propTypes用于限定屬性message的類型為string。constructor是我們組件的構造方法,有一個props參數(shù),此參數(shù)為傳遞過來的一些屬性。需要注意,構造方法中首先要調用super(props),否則報錯,在此處,我將傳遞來的值設置到了state中。

對于Toast,顯示一會兒自動消失,我們可以通過setTimeout實現(xiàn)這個效果,在componentDidMount調用此方法,此處設置時間為1000ms。然后將隱藏毀掉暴露出去。當我們使用setTimeout時還需要在組件卸載時清除定時器。組件卸載時回調的時componentWillUnmount。所以在此處清除定時器。

實現(xiàn)動畫效果

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

在組件中增加兩個變量

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轉變執(zhí)行時間100ms。在上面我們看到有個easing屬性,該屬性傳的是動畫執(zhí)行的曲線速度,可以自己實現(xiàn),在Easing API中已經有多種不同的效果。大家可以自己去看看實現(xiàn),源碼地址是 https://github.com/facebook/react-native/blob/master/Libraries/Animated/src/Easing.js ,自己實現(xiàn)的話直接給一個計算函數(shù)就可以,可以自己去看模仿。

定義顯示時間

在前面我們設置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 : '',
      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 '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就是我們定義的根組件,實現(xiàn)如上,通過AppRegistry.registerComponent注冊。

包裝供外部調用

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

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

使用

首先導入上面的Toast,然后通過下面方法調用

Toast.show("測試,我是Toast");
          //能設置顯示時間的Toast
          Toast.show("測試",Toast.LONG);

好了文章介紹完畢。如果想看完整代碼,可以進我 GitHub 查看。文中若有不足或錯誤的地方歡迎指出。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。最后新年快樂。

相關文章

  • 解決React報錯Cannot?find?namespace?context

    解決React報錯Cannot?find?namespace?context

    這篇文章主要為大家介紹了React報錯Cannot?find?namespace?context分析解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • 詳解如何在React函數(shù)式組件中使用MobX

    詳解如何在React函數(shù)式組件中使用MobX

    MobX 是一個簡潔的狀態(tài)管理庫,它通過透明的函數(shù)響應式編程(TFRP)使得狀態(tài)管理變得簡單和可擴展,下面就跟隨小編一起來了解一下如何在React函數(shù)式組件中使用MobX吧
    2024-01-01
  • React Native如何消除啟動時白屏的方法

    React Native如何消除啟動時白屏的方法

    本篇文章主要介紹了React Native如何消除啟動時白屏的方法,詳細的介紹了解決的方法,具有一定的參考價值,有興趣的可以了解一下
    2017-08-08
  • React高級特性Context萬字詳細解讀

    React高級特性Context萬字詳細解讀

    React的context就是一個全局變量,可以從根組件跨級別在React的組件中傳遞。React context的API有兩個版本,React16.x之前的是老版本的context,之后的是新版本的context
    2022-11-11
  • React videojs 實現(xiàn)自定義組件(視頻畫質/清晰度切換) 的操作代碼

    React videojs 實現(xiàn)自定義組件(視頻畫質/清晰度切換) 的操作代碼

    最近使用videojs作為視頻處理第三方庫,用來對接m3u8視頻類型,這里總結一下自定義組件遇到的問題及實現(xiàn),感興趣的朋友跟隨小編一起看看吧
    2023-08-08
  • 基于React編寫一個全局Toast的示例代碼

    基于React編寫一個全局Toast的示例代碼

    前些日子在做項目的時候,需要封裝一個Toast組件,我想起之前用過的庫,只要在入口文件中引入就可以在全局中使用,還是很方便的,借這次機會也來實現(xiàn)一下,所以本文介紹了React中如何編寫一個全局Toast,需要的朋友可以參考下
    2024-05-05
  • React中的ref屬性的使用示例詳解

    React中的ref屬性的使用示例詳解

    React 提供了 refrefref 屬性,讓我們可以引用組件的實例或者原生 DOM 元素,使用 refrefref,可以在父組件中調用子組件暴露出來的方法,或者調用原生 element 的 API,這篇文章主要介紹了React中的ref屬性的使用,需要的朋友可以參考下
    2023-04-04
  • React組件的生命周期深入理解分析

    React組件的生命周期深入理解分析

    組件的生命周期就是React的工作過程,就好比人有生老病死,自然界有日月更替,每個組件在網(wǎng)頁中也會有被創(chuàng)建、更新和刪除,如同有生命的機體一樣
    2022-12-12
  • React-Hooks之useImperativeHandler使用介紹

    React-Hooks之useImperativeHandler使用介紹

    這篇文章主要為大家介紹了React-Hooks之useImperativeHandler使用介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • React三大屬性之props的使用詳解

    React三大屬性之props的使用詳解

    這篇文章主要介紹了React三大屬性之props的使用詳解,幫助大家更好的理解和學習使用React,感興趣的朋友可以了解下
    2021-04-04

最新評論