ホームページ  >  記事  >  ウェブフロントエンド  >  ReactNativeを使用してToastを実装する方法

ReactNativeを使用してToastを実装する方法

亚连
亚连オリジナル
2018-06-14 15:15:242274ブラウズ

この記事では主に ReactNative で Toast を実装する例を紹介しますので、参考にしてください。

Android 開発エンジニアにとって、Toast はプロンプト メッセージを表示したり、自動的に非表示にしたりするために使用されます。 RN アプリケーションを開発する場合、このような効果を実現するのは少し難しいですが、RN が正式に提供する API ToastAndroid を採用するだけで、まったく難しいことではありません。これは Android でのみ使用でき、iOS で使用すると効果がありません。そのため、今日の記事では、Android と iOS の両方で実行できるように Toast をカスタマイズする必要があります。操作効果。

ソースコードポータル

コンポーネントを定義します

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をインポートし、カスタムコンポーネントはそれを継承する必要があります。アニメーションを実装するためにディメンションが使用され、アニメーションの軌道実行効果を設定するためにイージングが使用されます。 PropTypes 属性タイプを定義するために使用されます。

render メソッドは、コンポーネントのレンダリングを定義するためのエントリ ポイントです。最も外側のビューは位置を絶対値として使用し、画面全体に表示されるように左、右、上、下を 0 に設定します。トースト表示中のクリックを監視することはできません。内側の View は Toast で表示される黒いフレームのコンテナで、backgroundColor 属性は rgba 形式に設定されており、色は黒、透明度は 0.6 です。そして角丸と最大幅を画面幅の半分に設定します。次に、Text コンポーネントを使用して特定のプロンプト情報を表示します。

属性メッセージのタイプを文字列に制限するために propTypes が使用されていることもわかります。コンストラクターはコンポーネントの構築メソッドであり、渡されるプロパティである props パラメーターを持っています。 super(props) はコンストラクターで最初に呼び出す必要があることに注意してください。そうしないと、エラーが報告されます。ここでは、渡された値を状態に設定します。

トーストの場合、表示はしばらくすると自動的に消えます。この効果は、componentDidMount でこのメソッドを呼び出すことで実現できます。この時間は 1000 ミリ秒に設定されています。そして隠された破壊が暴露される。 setTimeout を使用する場合、コンポーネントがアンロードされるときにタイマーをクリアする必要もあります。コンポーネントがアンマウントされると、componentWillUnmount がコールバックされます。ここでタイマーをクリアします。

アニメーション効果を実現

上記でトースト効果を実装しましたが、表示と非表示がアニメーションしすぎず、少し硬いです。次に、移動と透明度のアニメーションを追加し、componentDidMount を変更してアニメーション効果を実現します

コンポーネントに 2 つの変数を追加します

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

内部ビューの以前のスタイルでは、下部セットは高さ/8 でした。ここでは、ビュー スタイルを次のように設定します

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

を変更します。つまり、一番下が表示されると、高さ/12 から高さ/8 に移動し、時間は 80 ミリ秒で、 0 から 1 までの透明度の変化は 100ms です。上では、アニメーション実行のカーブ速度を渡すイージング属性があることがわかります。イージング API にはさまざまな効果があります。自分で実装したい場合は、ソース コードのアドレスは https://github.com/facebook/react-native/blob/master/Libraries/Animated/src/Easing.js です。計算機能を付けてみましょう。

表示時間を定義します

前のステップでは、表示時間をカスタマイズし、タイプを数値に限定しました

time: PropTypes.number

コンストラクターでの時間の処理

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

をここに示します。時間を表示 SHORT と LONG の 2 つの値に処理されます。もちろん、自分で希望の効果に処理することもできます。

その後、timingDismiss の時刻 1000 を変更して this.state.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()
  }

コンポーネントの登録

定義したコンポーネントを render メソッドに記述するのではなく API の形式で呼び出すために、フォローコンポーネントを定義します

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

実装は、定義したルートコンポーネントです。上記と同様に、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

外部使用の表示時間を表す 2 つの静的変数が Toast で定義されています。次に、2 つの静的メソッドを提供します。このメソッドでは、RootView の setView メソッドを呼び出して、ToastView をルート ビューに設定します。

を使用するには、まず上記の Toast をインポートし、次のメソッドで

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

を呼び出します。

関連記事:

webpackを使用してvueスキャフォールディングを構築する

webpackを使用してファイルパッケージ化を実装する方法

webpackの構築の詳細な紹介

以上がReactNativeを使用してToastを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。