H5端API库,为Taro跨端开发框架提供Web/H5端的API实现
—
Browser-based user interface interaction APIs including toast messages, modals, loading indicators, and action sheets for providing native-like user interface components in web environments.
Display temporary notification messages with customizable appearance and duration.
/**
* Show toast notification message
* @param options - Toast configuration options
* @returns Promise that resolves when toast is displayed
*/
function showToast(options: ToastOption): Promise<void>;
/**
* Hide currently displayed toast message
* @param options - Optional callback configuration
* @returns Promise that resolves when toast is hidden
*/
function hideToast(options?: CallbackOptions): Promise<void>;
interface ToastOption extends CallbackOptions {
/** Toast message text (required) */
title: string;
/** Icon type to display with message */
icon?: 'success' | 'error' | 'loading' | 'none';
/** Custom image URL (overrides icon) */
image?: string;
/** Display duration in milliseconds (default: 1500) */
duration?: number;
/** Whether to show overlay mask preventing interaction (default: false) */
mask?: boolean;
}Usage Examples:
import { showToast, hideToast } from "@tarojs/taro-h5";
// Success toast
await showToast({
title: 'Saved successfully!',
icon: 'success',
duration: 2000
});
// Error toast
await showToast({
title: 'Network error occurred',
icon: 'error',
duration: 3000
});
// Loading toast with mask
await showToast({
title: 'Processing...',
icon: 'loading',
mask: true,
duration: 0 // Show indefinitely
});
// Hide loading toast manually
setTimeout(() => {
hideToast();
}, 5000);
// Text-only toast
await showToast({
title: 'This is a simple message',
icon: 'none',
duration: 2000
});
// Custom image toast
await showToast({
title: 'Achievement unlocked!',
image: '/path/to/custom-icon.png',
duration: 2500
});
// With callbacks
showToast({
title: 'Operation completed',
icon: 'success',
success: () => {
console.log('Toast displayed');
},
complete: () => {
console.log('Toast operation finished');
}
});Display loading indicators with customizable messages and overlay behavior.
/**
* Show loading indicator
* @param options - Loading configuration options
* @returns Promise that resolves when loading indicator is displayed
*/
function showLoading(options: LoadingOption): Promise<void>;
/**
* Hide currently displayed loading indicator
* @param options - Optional callback configuration
* @returns Promise that resolves when loading indicator is hidden
*/
function hideLoading(options?: CallbackOptions): Promise<void>;
interface LoadingOption extends CallbackOptions {
/** Loading message text (default: 'Loading...') */
title?: string;
/** Whether to show overlay mask preventing interaction (default: true) */
mask?: boolean;
}Usage Examples:
import { showLoading, hideLoading } from "@tarojs/taro-h5";
// Basic loading indicator
await showLoading({
title: 'Loading...'
});
// Simulate async operation
setTimeout(async () => {
await hideLoading();
await showToast({
title: 'Data loaded!',
icon: 'success'
});
}, 3000);
// Loading with custom message
await showLoading({
title: 'Uploading files...',
mask: true
});
// Loading without mask (allows user interaction)
await showLoading({
title: 'Syncing in background',
mask: false
});
// Async operation with loading
async function fetchUserData() {
try {
await showLoading({ title: 'Fetching user data...' });
const userData = await request({
url: '/api/user/profile',
method: 'GET'
});
await hideLoading();
return userData;
} catch (error) {
await hideLoading();
await showToast({
title: 'Failed to load user data',
icon: 'error'
});
throw error;
}
}Display modal dialog boxes with customizable buttons and content for user confirmations and alerts.
/**
* Show modal dialog
* @param options - Modal configuration options
* @returns Promise resolving to user's choice
*/
function showModal(options: ModalOption): Promise<ModalResult>;
interface ModalOption extends CallbackOptions {
/** Modal title text */
title?: string;
/** Modal body content text (required) */
content: string;
/** Whether to show cancel button (default: true) */
showCancel?: boolean;
/** Cancel button text (default: 'Cancel') */
cancelText?: string;
/** Cancel button text color (default: '#000000') */
cancelColor?: string;
/** Confirm button text (default: 'OK') */
confirmText?: string;
/** Confirm button text color (default: '#576B95') */
confirmColor?: string;
/** Whether to enable HTML content (default: false) */
editable?: boolean;
/** Placeholder text for editable input */
placeholderText?: string;
}
interface ModalResult {
/** Whether confirm button was clicked */
confirm: boolean;
/** Whether cancel button was clicked */
cancel: boolean;
/** Input text content (if editable is true) */
content?: string;
}Usage Examples:
import { showModal } from "@tarojs/taro-h5";
// Basic confirmation dialog
const confirmResult = await showModal({
title: 'Confirm Delete',
content: 'Are you sure you want to delete this item?',
showCancel: true,
confirmText: 'Delete',
confirmColor: '#ff4444'
});
if (confirmResult.confirm) {
console.log('User confirmed deletion');
// Proceed with deletion
} else {
console.log('User cancelled deletion');
}
// Alert dialog (no cancel button)
await showModal({
title: 'Information',
content: 'Your data has been saved successfully.',
showCancel: false,
confirmText: 'Got it'
});
// Custom styled modal
const customResult = await showModal({
title: 'Warning',
content: 'This action cannot be undone. Continue?',
showCancel: true,
cancelText: 'Go Back',
cancelColor: '#666666',
confirmText: 'Continue',
confirmColor: '#ff6600'
});
// Input modal (if supported)
const inputResult = await showModal({
title: 'Enter Name',
content: 'Please enter your name:',
editable: true,
placeholderText: 'Your name',
confirmText: 'Submit'
});
if (inputResult.confirm && inputResult.content) {
console.log('User entered:', inputResult.content);
}
// Error confirmation
async function confirmDangerousAction() {
const result = await showModal({
title: 'Danger Zone',
content: 'This will permanently delete all your data. This action cannot be undone.',
showCancel: true,
cancelText: 'Keep Data',
confirmText: 'Delete All',
confirmColor: '#ff0000'
});
return result.confirm;
}Display action sheets with multiple selectable options for user choice scenarios.
/**
* Show action sheet with multiple options
* @param options - Action sheet configuration
* @returns Promise resolving to user's selection
*/
function showActionSheet(options: ActionSheetOption): Promise<ActionSheetResult>;
interface ActionSheetOption extends CallbackOptions {
/** List of button text options (required) */
itemList: string[];
/** Button text colors (optional, matches itemList length) */
itemColor?: string[];
/** Alert text displayed above options */
alertText?: string;
}
interface ActionSheetResult {
/** Index of selected item (0-based) */
tapIndex: number;
}Usage Examples:
import { showActionSheet } from "@tarojs/taro-h5";
// Basic action sheet
const actionResult = await showActionSheet({
itemList: ['Take Photo', 'Choose from Album', 'Cancel']
});
switch (actionResult.tapIndex) {
case 0:
console.log('User chose to take photo');
// Open camera
break;
case 1:
console.log('User chose to select from album');
// Open photo picker
break;
case 2:
console.log('User cancelled');
break;
}
// Action sheet with custom colors
const colorResult = await showActionSheet({
itemList: ['Delete', 'Archive', 'Share', 'Cancel'],
itemColor: ['#ff4444', '#666666', '#0066cc', '#999999'],
alertText: 'Choose an action for this item'
});
// Share action sheet
async function showShareOptions() {
const shareResult = await showActionSheet({
itemList: [
'Share to WeChat',
'Share to Weibo',
'Copy Link',
'More Options',
'Cancel'
],
alertText: 'Share this content'
});
const actions = ['wechat', 'weibo', 'copylink', 'more', 'cancel'];
const selectedAction = actions[shareResult.tapIndex];
console.log('Selected share action:', selectedAction);
return selectedAction;
}
// Settings action sheet
async function showSettingsMenu() {
const settingsResult = await showActionSheet({
itemList: [
'Edit Profile',
'Privacy Settings',
'Notification Settings',
'Help & Support',
'Sign Out',
'Cancel'
],
itemColor: [
'#333333', // Edit Profile
'#333333', // Privacy Settings
'#333333', // Notification Settings
'#0066cc', // Help & Support
'#ff4444', // Sign Out (red)
'#999999' // Cancel (gray)
]
});
const menuActions = [
'editProfile',
'privacy',
'notifications',
'help',
'signOut',
'cancel'
];
return menuActions[settingsResult.tapIndex];
}Complex interaction patterns and best practices for UI components.
// Chained interactions
async function deleteItemWithConfirmation(itemId: string) {
// First show action sheet
const actionResult = await showActionSheet({
itemList: ['Edit', 'Share', 'Delete', 'Cancel'],
itemColor: ['#333', '#0066cc', '#ff4444', '#999'],
alertText: 'Choose an action'
});
if (actionResult.tapIndex === 2) { // Delete selected
// Show confirmation modal
const confirmResult = await showModal({
title: 'Confirm Delete',
content: 'This item will be permanently deleted. Continue?',
confirmText: 'Delete',
confirmColor: '#ff4444'
});
if (confirmResult.confirm) {
// Show loading
await showLoading({ title: 'Deleting...' });
try {
await deleteItem(itemId);
await hideLoading();
// Show success toast
await showToast({
title: 'Item deleted',
icon: 'success'
});
return true;
} catch (error) {
await hideLoading();
await showToast({
title: 'Delete failed',
icon: 'error'
});
return false;
}
}
}
return false;
}
// Progress feedback pattern
async function uploadWithProgress(file: File) {
await showLoading({ title: 'Preparing upload...' });
try {
// Prepare upload
await new Promise(resolve => setTimeout(resolve, 1000));
await hideLoading();
await showLoading({ title: 'Uploading...' });
// Simulate upload progress
for (let i = 1; i <= 5; i++) {
await new Promise(resolve => setTimeout(resolve, 500));
await hideLoading();
await showLoading({ title: `Uploading... ${i * 20}%` });
}
await hideLoading();
await showToast({
title: 'Upload completed!',
icon: 'success',
duration: 2000
});
} catch (error) {
await hideLoading();
await showModal({
title: 'Upload Failed',
content: 'The file could not be uploaded. Please try again.',
showCancel: false
});
}
}
// Smart error handling
class UIInteractionHelper {
static async showError(message: string, details?: string): Promise<boolean> {
if (details) {
return (await showModal({
title: 'Error',
content: `${message}\n\nDetails: ${details}`,
showCancel: true,
cancelText: 'Dismiss',
confirmText: 'Retry'
})).confirm;
} else {
await showToast({
title: message,
icon: 'error',
duration: 3000
});
return false;
}
}
static async showSuccess(message: string): Promise<void> {
await showToast({
title: message,
icon: 'success',
duration: 2000
});
}
static async confirmAction(
title: string,
message: string,
actionText: string = 'Confirm'
): Promise<boolean> {
const result = await showModal({
title,
content: message,
confirmText: actionText,
confirmColor: '#0066cc'
});
return result.confirm;
}
static async selectOption(
title: string,
options: string[],
colors?: string[]
): Promise<number | null> {
try {
const result = await showActionSheet({
itemList: options,
itemColor: colors,
alertText: title
});
return result.tapIndex;
} catch {
return null; // User cancelled
}
}
}
// Usage of helper
async function handleUserAction() {
const option = await UIInteractionHelper.selectOption(
'Choose action',
['Save', 'Discard', 'Cancel'],
['#0066cc', '#ff6600', '#999']
);
switch (option) {
case 0: // Save
const confirmed = await UIInteractionHelper.confirmAction(
'Save Changes',
'Save your changes?',
'Save'
);
if (confirmed) {
await UIInteractionHelper.showSuccess('Changes saved!');
}
break;
case 1: // Discard
const shouldDiscard = await UIInteractionHelper.confirmAction(
'Discard Changes',
'All unsaved changes will be lost. Continue?',
'Discard'
);
if (shouldDiscard) {
await UIInteractionHelper.showSuccess('Changes discarded');
}
break;
default: // Cancel or null
console.log('Action cancelled');
}
}interface CallbackOptions {
success?: (res: any) => void;
fail?: (err: any) => void;
complete?: (res: any) => void;
}
type ToastIcon = 'success' | 'error' | 'loading' | 'none';
type ButtonColor = string; // CSS color valueInstall with Tessl CLI
npx tessl i tessl/npm-tarojs--taro-h5