Bài 49: Toast Timg hiểu ion-toast

Bài 49: Toast Timg hiểu ion-toast

  

 ion-toast

Toast  là một thông báo tinh tế thường được sử dụng trong các ứng dụng hiện đại. Nó có thể được sử dụng để cung cấp phản hồi về một hoạt động hoặc để hiển thị thông báo hệ thống. Toast xuất hiện trên đầu nội dung của ứng dụng và có thể được ứng dụng loại bỏ để tiếp tục tương tác của người dùng với ứng dụng.



Positioning

Toasts có thể được đặt ở trên cùng, dưới cùng hoặc giữa khung nhìn. Vị trí có thể được thông qua khi tạo. Các giá trị có thể là top, bottom và middle. Nếu vị trí không được chỉ định, Toasts sẽ được hiển thị ở cuối khung nhìn.

Dismissing

toast  có thể tự động bị loại bỏ sau một khoảng thời gian cụ thể bằng cách chuyển số mili giây để hiển thị trong các duration tùy chọn toast . Nếu một nút có vai trò "cancel"được thêm vào, thì nút đó sẽ loại bỏ lời chúc mừnAdded. Để loại bỏ Toast sau khi tạo, hãy gọi dismiss() phương thức trên phiên bản.

Usage

import { Component } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'toast-example',
  templateUrl: 'toast-example.html',
  styleUrls: ['./toast-example.css'],
})
export class ToastExample {

  constructor(public toastController: ToastController) {}

  async presentToast() {
    const toast = await this.toastController.create({
      message: 'Your settings have been saved.',
      duration: 2000
    });
    toast.present();
  }

  async presentToastWithOptions() {
    const toast = await this.toastController.create({
      header: 'Toast header',
      message: 'Click to Close',
      position: 'top',
      buttons: [
        {
          side: 'start',
          icon: 'star',
          text: 'Favorite',
          handler: () => {
            console.log('Favorite clicked');
          }
        }, {
          text: 'Done',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    await toast.present();

    const { role } = await toast.onDidDismiss();
    console.log('onDidDismiss resolved with role', role);
  }

}
async function presentToast() {
  const toast = document.createElement('ion-toast');
  toast.message = 'Your settings have been saved.';
  toast.duration = 2000;

  document.body.appendChild(toast);
  return toast.present();
}

async function presentToastWithOptions() {
  const toast = document.createElement('ion-toast');
  toast.header = 'Toast header';
  toast.message = 'Click to Close';
  toast.position = 'top';
  toast.buttons = [
    {
      side: 'start',
      icon: 'star',
      text: 'Favorite',
      handler: () => {
        console.log('Favorite clicked');
      }
    }, {
      text: 'Done',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }
  ];

  document.body.appendChild(toast);
  await toast.present();

  const { role } = await toast.onDidDismiss();
  console.log('onDidDismiss resolved with role', role);
}
/* Using the useIonToast Hook */

import React from 'react';
import { IonButton, IonContent, IonPage, useIonToast } from '@ionic/react';

const ToastExample: React.FC = () => {
  const [present, dismiss] = useIonToast();

  return (
    <IonPage>
      <IonContent>
        <IonButton
          expand="block"
          onClick={() =>
            present({
              buttons: [{ text: 'hide', handler: () => dismiss() }],
              message: 'toast from hook, click hide to dismiss',
              onDidDismiss: () => console.log('dismissed'),
              onWillDismiss: () => console.log('will dismiss'),
            })
          }
        >
          Show Toast
        </IonButton>
        <IonButton
          expand="block"
          onClick={() => present('hello from hook', 3000)}
        >
          Show Toast using params, closes in 3 secs
        </IonButton>
        <IonButton expand="block" onClick={dismiss}>
          Hide Toast
        </IonButton>
      </IonContent>
    </IonPage>
  );
};
CopyCopied
/* Using the IonToast Component */

import React, { useState } from 'react';
import { IonToast, IonContent, IonButton } from '@ionic/react';

export const ToastExample: React.FC = () => {
  const [showToast1, setShowToast1] = useState(false);
  const [showToast2, setShowToast2] = useState(false);

  return (
    <IonContent>
      <IonButton onClick={() => setShowToast1(true)} expand="block">Show Toast 1</IonButton>
      <IonButton onClick={() => setShowToast2(true)} expand="block">Show Toast 2</IonButton>
      <IonToast
        isOpen={showToast1}
        onDidDismiss={() => setShowToast1(false)}
        message="Your settings have been saved."
        duration={200}
      />

      <IonToast
        isOpen={showToast2}
        onDidDismiss={() => setShowToast2(false)}
        message="Click to Close"
        position="top"
        buttons={[
          {
            side: 'start',
            icon: 'star',
            text: 'Favorite',
            handler: () => {
              console.log('Favorite clicked');
            }
          },
          {
            text: 'Done',
            role: 'cancel',
            handler: () => {
              console.log('Cancel clicked');
            }
          }
        ]}
      />
    </IonContent>
  );
};


import { Component, h } from '@stencil/core';

import { toastController } from '@ionic/core';

@Component({
  tag: 'toast-example',
  styleUrl: 'toast-example.css'
})
export class ToastExample {
  async presentToast() {
    const toast = await toastController.create({
      message: 'Your settings have been saved.',
      duration: 2000
    });
    toast.present();
  }

  async presentToastWithOptions() {
    const toast = await toastController.create({
      header: 'Toast header',
      message: 'Click to Close',
      position: 'top',
      buttons: [
        {
          side: 'start',
          icon: 'star',
          text: 'Favorite',
          handler: () => {
            console.log('Favorite clicked');
          }
        }, {
          text: 'Done',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    await toast.present();

    const { role } = await toast.onDidDismiss();
    console.log('onDidDismiss resolved with role', role);
  }

  render() {
    return [
      <ion-content>
        <ion-button onClick={() => this.presentToast()}>Present Toast</ion-button>
        <ion-button onClick={() => this.presentToastWithOptions()}>Present Toast: Options</ion-button>
      </ion-content>
    ];
  }
}
<template>
  <ion-page>
    <ion-content class="ion-padding">
      <ion-button @click="openToast">Open Toast</ion-button>
      <ion-button @click="openToastOptions">Open Toast: Options</ion-button>
    </ion-content>
  </ion-page>
</template>

<script>
import { IonButton, IonContent, IonPage, toastController } from '@ionic/vue';

export default {
  components: { IonButton, IonContent, IonPage },
  methods: {
    async openToast() {
      const toast = await toastController
        .create({
          message: 'Your settings have been saved.',
          duration: 2000
        })
      return toast.present();
    },
    async openToastOptions() {
      const toast = await toastController
        .create({
          header: 'Toast header',
          message: 'Click to Close',
          position: 'top',
          buttons: [
            {
              side: 'start',
              icon: 'star',
              text: 'Favorite',
              handler: () => {
                console.log('Favorite clicked');
              }
            }, {
              text: 'Done',
              role: 'cancel',
              handler: () => {
                console.log('Cancel clicked');
              }
            }
          ]
        })
      await toast.present();

      const { role } = await toast.onDidDismiss();
      console.log('onDidDismiss resolved with role', role);
    },
  },
}
</script>
CopyCopied

Developers can also use this component directly in their template:

<template>
  <ion-button @click="setOpen(true)">Show Toast</ion-button>
  <ion-toast
    :is-open="isOpenRef"
    message="Your settings have been saved."
    :duration="2000"
    @didDismiss="setOpen(false)"
  >
  </ion-toast>
</template>

<script>
import { IonToast, IonButton } from '@ionic/vue';
import { defineComponent, ref } from 'vue';

export default defineComponent({
  components: { IonToast, IonButton },
  setup() {
    const isOpenRef = ref(false);
    const setOpen = (state: boolean) => isOpenRef.value = state;

    return { isOpenRef, setOpen }
  }
});
</script>

Properties


animated

Description

If true, the toast will animate.

Attributeanimated
Typeboolean
Defaulttrue

buttons

Description

An array of buttons for the toast.

Type(string | ToastButton)[] | undefined

color

Description

The color to use from your application's color palette. Default options are: "primary""secondary""tertiary""success""warning""danger""light""medium", and "dark". For more information on colors, see theming.

Attributecolor
Typestring | undefined

cssClass

Description

Additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces.

Attributecss-class
Typestring | string[] | undefined

duration

Description

How many milliseconds to wait before hiding the toast. By default, it will show until dismiss() is called.

Attributeduration
Typenumber
Default0

enterAnimation

Description

Animation to use when the toast is presented.

Type((baseEl: any, opts?: any) => Animation) | undefined

header

Description

Header to be shown in the toast.

Attributeheader
Typestring | undefined

keyboardClose

Description

If true, the keyboard will be automatically dismissed when the overlay is presented.

Attributekeyboard-close
Typeboolean
Defaultfalse

leaveAnimation

Description

Animation to use when the toast is dismissed.

Type((baseEl: any, opts?: any) => Animation) | undefined

message

Description

Message to be shown in the toast.

Attributemessage
TypeIonicSafeString | string | undefined

mode

Description

The mode determines which platform styles to use.

Attributemode
Type"ios" | "md"

position

Description

The position of the toast on the screen.

Attributeposition
Type"bottom" | "middle" | "top"
Default'bottom'

translucent

Description

If true, the toast will be translucent. Only applies when the mode is "ios" and the device supports backdrop-filter.

Attributetranslucent
Typeboolean
Defaultfalse

Events

NameDescription
ionToastDidDismissEmitted after the toast has dismissed.
ionToastDidPresentEmitted after the toast has presented.
ionToastWillDismissEmitted before the toast has dismissed.
ionToastWillPresentEmitted before the toast has presented.

Methods

dismiss

Description

Dismiss the toast overlay after it has been presented.

Signaturedismiss(data?: any, role?: string | undefined) => Promise<boolean>

onDidDismiss

Description

Returns a promise that resolves when the toast did dismiss.

SignatureonDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>

onWillDismiss

Description

Returns a promise that resolves when the toast will dismiss.

SignatureonWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>

present

Description

Present the toast overlay after it has been created.

Signaturepresent() => Promise<void>

CSS Shadow Parts

NameDescription
buttonAny button element that is displayed inside of the toast.
containerThe element that wraps all child elements.
headerThe header text of the toast.
messageThe body text of the toast.

CSS Custom Properties

NameDescription
--backgroundBackground of the toast
--border-colorBorder color of the toast
--border-radiusBorder radius of the toast
--border-styleBorder style of the toast
--border-widthBorder width of the toast
--box-shadowBox shadow of the toast
--button-colorColor of the button text
--colorColor of the toast text
--endPosition from the right if direction is left-to-right, and from the left if direction is right-to-left
--heightHeight of the toast
--max-heightMaximum height of the toast
--max-widthMaximum width of the toast
--min-heightMinimum height of the toast
--min-widthMinimum width of the toast
--startPosition from the left if direction is left-to-right, and from the right if direction is right-to-left
--white-spaceWhite space of the toast message
--widthWidth of the toast

Đăng nhận xét

0 Nhận xét

myadcash