Menu cơ bản
Nút + nở thành thẻ menu; mỗi dòng nở thành một route toàn màn hình rồi thu lại khi đóng.
Hoạt động thế nào
Phần tiêu đề “Hoạt động thế nào”- Bấm + để mở thẻ, rồi chọn một dòng: thẻ nở thành route
/(sheet)/[key]. Hoặc nhấn giữ +, trượt lên một dòng rồi thả tay. MorphProvidertrong root layout giữ danh sách item;<MorphMenu />đặt sauStackvẽ nút và thẻ lên trên mọi màn hình.- Nhóm
(sheet)được khai báo vớimorphSheetScreenOptions, layout của nó làMorphSheetLayout: mọi route bên trong đều nở ra từ thẻ. - Màn hình hiện skeleton cho tới khi
useMorphSettled()là true, nên hiệu ứng nở không phải chờ nội dung nặng.onHovertải trước dữ liệu của dòng đang được rê chuột. - Đóng bằng nút × (
MorphCloseButton), nút back của trình duyệt hoặc Esc: màn hình thu về thẻ, và menu vẫn mở.
Dùng
Mã nguồn đầy đủ
Phần tiêu đề “Mã nguồn đầy đủ”Đây chính là mã đang chạy trong khung điện thoại. Chép về, đổi item và màn hình là dùng được.
import { Ionicons } from '@expo/vector-icons';import { Stack, useGlobalSearchParams } from 'expo-router';import { MorphMenu, MorphProvider, MorphTrace, morphSheetScreenOptions } from 'expo-morph-menu';import { StatusBar } from 'expo-status-bar';import { useMemo, useState } from 'react';import { GestureHandlerRootView } from 'react-native-gesture-handler';import { SafeAreaProvider } from 'react-native-safe-area-context';
import { CUSTOM_COMPONENTS, CUSTOM_CONFIG, customItemHeight } from '../components/CustomSlots';import { DemoContext, type UiVariant } from '../context/demo';import { ITEMS } from '../data/items';import { findScene } from '../scenes';import { prefetchSheet } from '../data/sheetData';
/** `npm run example:trace` enables the per-frame trace used by the end-to-end tests. */const TRACE = process.env.EXPO_PUBLIC_MORPH_TRACE === '1';
/** A deep link into the sheet keeps the home screen below it, so closing has a screen to return to. */export const unstable_settings = { anchor: 'index' };
export default function RootLayout() { // The documentation site opens the demo with a scene, a variant or a corner // in the URL, for example /?scene=wallet, /?variant=custom or /?anchor=left. // Read once, at start; on a phone the home screen switches them. const params = useGlobalSearchParams<{ scene?: string; variant?: string; anchor?: string }>(); const [sceneId, setScene] = useState(() => findScene(params.scene)?.id ?? 'basic'); const scene = findScene(sceneId); const [variant, setVariant] = useState<UiVariant>(() => params.variant === 'custom' ? 'custom' : 'default', ); const [anchor] = useState<'bottom-left' | 'bottom-right'>(() => params.anchor === 'left' ? 'bottom-left' : 'bottom-right', ); const demo = useMemo(() => ({ variant, setVariant, scene: sceneId, setScene }), [variant, sceneId]); const custom = variant === 'custom';
return ( <SafeAreaProvider> <GestureHandlerRootView style={{ flex: 1 }}> <DemoContext.Provider value={demo}> <MorphProvider // Another demo app is another menu: start it fresh. key={sceneId} items={scene?.items ?? ITEMS} // Called while the pointer is on a row, before the row is selected. onHover={(item) => prefetchSheet(item.key)} // Icon for every <MorphCloseButton>: an element, an image source, or a function. closeIcon={({ size, color }) => <Ionicons name="close" size={size} color={color} />} // The custom variant replaces every visible part through slots. components={scene ? scene.components : custom ? CUSTOM_COMPONENTS : undefined} itemHeight={scene ? scene.itemHeight : custom ? customItemHeight : undefined} fabIcon={scene?.fabIcon} // The screens of this app are light only, so the close button uses light colors too. config={ scene ? { colorScheme: 'light', ...scene.config } : custom ? { ...CUSTOM_CONFIG, colorScheme: 'light', anchor } : { colorScheme: 'light', anchor } } > <Stack screenOptions={{ headerShown: false }}> <Stack.Screen name="index" /> <Stack.Screen name="(sheet)" options={morphSheetScreenOptions} /> </Stack>
{/* After the navigator, so the button and the card are drawn above every screen. The menu has no route of its own. */} <MorphMenu /> {TRACE && <MorphTrace />} <StatusBar style={scene?.config?.colorScheme === 'dark' ? 'light' : 'dark'} /> </MorphProvider> </DemoContext.Provider> </GestureHandlerRootView> </SafeAreaProvider> );}import { Stack } from 'expo-router';import { MorphSheetLayout } from 'expo-morph-menu';
/** Every route in the (sheet) group expands from the menu card and collapses back into it. */export default function SheetLayout() { return ( <MorphSheetLayout> <Stack.Screen name="[key]" options={{ headerShown: false }} /> </MorphSheetLayout> );}import { Ionicons } from '@expo/vector-icons';import { Link, useLocalSearchParams } from 'expo-router';import { MorphCloseButton, useMorph, useMorphSettled } from 'expo-morph-menu';import { Platform, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Skeleton } from '../../components/Skeleton';import { useDemo } from '../../context/demo';import { findScene } from '../../scenes';import { findDemo } from '../../data/items';import { useSheetData } from '../../data/sheetData';import { column } from '../../components/layout';
/** Lists the ways to close this screen that are enabled in the config. */function closeHint(d: { edgeSwipe: boolean; dragDown: boolean }) { const ways = [ 'the close button', Platform.OS === 'android' && 'the back button', Platform.OS === 'web' && 'Esc or the browser back button', d.edgeSwipe && 'a swipe from the left edge', d.dragDown && 'dragging down', ].filter(Boolean); return `Close with ${ways.join(', ')}. Every way runs the same collapse animation back into the card.`;}
const PREFETCHED_MS = 80;
/** The screen of a row: the basic one below, or the running scene's own. */export default function SheetRoute() { const { key } = useLocalSearchParams<{ key: string }>(); const scene = findScene(useDemo().scene); const { colors } = useMorph(); if (!scene) return <SheetRoot />; // On a tablet the screen is a centered column on the sheet's background. return ( <View style={[styles.fill, { backgroundColor: colors.sheetBackground }]}> <View style={[styles.fill, column]}> <scene.Screen itemKey={key} /> </View> </View> );}
function SheetRoot() { const { key } = useLocalSearchParams<{ key: string }>(); const item = findDemo(key); const insets = useSafeAreaInsets(); const settled = useMorphSettled(); const { config } = useMorph(); const { data, waitedMs } = useSheetData(item.key);
// Render the content once the container has stopped moving and the data is here. const ready = settled && data !== null; const prefetched = waitedMs !== null && waitedMs < PREFETCHED_MS;
return ( <View style={styles.root}> <View style={[styles.header, { paddingTop: insets.top + 6 }]}> {/* The icon comes from `closeIcon` on MorphProvider (app/_layout.tsx). */} <MorphCloseButton accessibilityLabel="Close" /> <View style={styles.title}> <View style={[styles.icon, { backgroundColor: item.tint }]}> <Ionicons name={item.glyph} size={15} color="#fff" /> </View> <Text style={styles.titleText}>{item.label}</Text> </View> <View style={styles.ghost} /> </View>
{ready ? ( <ScrollView testID="sheet-content" // The container reaches the bottom edge, so leave room for the home indicator. contentContainerStyle={[column, styles.body, { paddingBottom: 24 + insets.bottom }]} > <Text style={styles.route}>/(sheet)/[key]?key={item.key}</Text> <Text style={styles.para}>{data.summary}</Text>
<View style={styles.badge}> <Ionicons name={prefetched ? 'flash' : 'hourglass-outline'} size={14} color={prefetched ? '#30d158' : '#8e8e93'} /> <Text style={styles.badgeText}> {prefetched ? `Waited ${waitedMs} ms. Loading started on hover.` : `Waited ${waitedMs} ms. Loading started when the screen opened.`} </Text> </View>
<Text style={styles.heading}>What happened</Text> <Text style={styles.para}> 1. The row's href was pushed with expo-router. This screen is a regular route, so a deep link opens it as well. </Text> <Text style={styles.para}> 2. MorphSheetLayout, the layout of the (sheet) group, animated the container from the card to full screen. </Text> <Text style={styles.para}> 3. This screen rendered a skeleton until useMorphSettled() returned true and the data arrived. </Text>
<Link href={{ pathname: '/(sheet)/child', params: { from: item.label } }} asChild> <Pressable style={styles.cta} testID="open-child"> <Text style={styles.ctaText}>Open a nested screen</Text> <Ionicons name="chevron-forward" size={16} color="#fff" /> </Pressable> </Link>
<Text style={styles.note}>{closeHint(config.dismiss)}</Text> </ScrollView> ) : ( <Skeleton /> )} </View> );}
const styles = StyleSheet.create({ fill: { flex: 1 }, root: { flex: 1, backgroundColor: '#fff' }, header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 16, paddingBottom: 10, }, title: { alignItems: 'center', gap: 4 }, titleText: { fontSize: 13, fontWeight: '600', color: '#1c1c1e' }, icon: { width: 26, height: 26, borderRadius: 13, alignItems: 'center', justifyContent: 'center', }, ghost: { width: 32 }, body: { padding: 24, gap: 14, alignItems: 'flex-start' }, route: { fontFamily: Platform.select({ ios: 'Menlo', default: 'monospace' }), fontSize: 12, color: '#8e8e93', }, heading: { fontSize: 17, fontWeight: '700', color: '#1c1c1e', marginTop: 6 }, badge: { flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: 'rgba(120,120,128,0.1)', paddingHorizontal: 10, paddingVertical: 6, borderRadius: 999, }, badgeText: { fontSize: 12, color: '#3a3a3c', fontWeight: '600' }, para: { fontSize: 15, color: '#3a3a3c', lineHeight: 22 }, cta: { flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: '#0a84ff', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 999, marginTop: 4, }, ctaText: { color: '#fff', fontSize: 15, fontWeight: '600' }, note: { fontSize: 13, color: '#8e8e93', lineHeight: 19 },});import { Ionicons } from '@expo/vector-icons';import type { MorphIcon, MorphItem } from 'expo-morph-menu';
type Demo = { key: string; label: string; /** Icon in the header of the sheet screen (drawn by this app). */ glyph: keyof typeof Ionicons.glyphMap; tint: string; /** Icon in the menu. The four items use the different MorphIcon forms. */ icon: MorphIcon; /** Used only by the custom Item slot (taller rows). */ subtitle?: string;};
/** Function form: receives `size` and `color` from the theme and config. */const ion = (name: keyof typeof Ionicons.glyphMap): MorphIcon => function IonIcon({ size, color }) { return <Ionicons name={name} size={size} color={color} />; };
const DEMO: Demo[] = [ { key: 'camera', label: 'Camera', glyph: 'camera', tint: '#3a3a3c', icon: ion('camera'), subtitle: 'Photos and video', }, { key: 'store', label: 'Store', glyph: 'logo-apple-appstore', tint: '#0a84ff', // Element form: sets its own size and color. icon: <Ionicons name="logo-apple-appstore" size={15} color="#fff" />, }, { key: 'audio', label: 'Audio', glyph: 'mic', tint: '#ff453a', icon: ion('mic'), subtitle: 'Voice memo' }, { key: 'checkin', label: 'Check In', glyph: 'locate', tint: '#ffd60a', // Image form: a single-color PNG tinted with colors.iconForeground. icon: require('../assets/target.png'), },];
/** Menu rows. Each row opens the route `/(sheet)/[key]`. */export const ITEMS: MorphItem[] = DEMO.map((d) => ({ key: d.key, label: d.label, tint: d.tint, icon: d.icon, data: d.subtitle ? { subtitle: d.subtitle } : undefined, href: { pathname: '/(sheet)/[key]', params: { key: d.key } },}));
export const findDemo = (key?: string): Demo => DEMO.find((d) => d.key === key) ?? DEMO[0];Xem trên GitHub: example/app/_layout.tsxXem trên GitHub: example/app/(sheet)/_layout.tsxXem trên GitHub: example/app/(sheet)/[key].tsxXem trên GitHub: example/data/items.tsx