Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo Expo iconExpo

Expo 及相关软件包的常用方法和类型集合。

Android
iOS
tvOS
Web
Included in Expo Go

安装

Terminal
- npx expo install expo
- yarn expo install expo
- pnpm expo install expo
- bun expo install expo

API

import * as Expo from 'expo';

expo/fetch API

expo/fetch 提供符合 WinterCG 规范的 Fetch API,可在 Web 和移动环境中保持一致地运行,确保 Expo 应用中的 fetch 体验标准化且跨平台。

Streaming fetch
import { fetch } from 'expo/fetch'; const resp = await fetch('https://httpbin.org/drip?numbytes=512&duration=2', { headers: { Accept: 'text/event-stream' }, }); const reader = resp.body.getReader(); const chunks = []; while (true) { const { done, value } = await reader.read(); if (done) { break; } chunks.push(value); } const buffer = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0)); console.log(buffer.length); // 512

编码 API

TextEncoder 和 TextDecoder 是内置 API,可用于对文本进行各种字符编码的编码和解码。它们在所有平台上均可用。有关 Web 和 Node.js 的支持情况,请参阅浏览器和服务器运行时支持。

TextEncoder and TextDecoder
// [104, 101, 108, 108, 111] const hello = new TextEncoder().encode('hello'); // "hello" const text = new TextDecoder().decode(hello);

TextEncoder API 已包含在 Hermes 引擎中。请参阅 Hermes GitHub 仓库中 TextEncoder.cpp 的源代码。

原生平台上的 TextDecoder API 不符合规范。目前仅支持 UTF-8 编码。如果需要支持更多编码,请使用 text-encoding 等 polyfill。

这些 API 对应的流式版本 TextEncoderStream 和 TextDecoderStream 也在所有平台上可用。它们允许以流式方式对文本进行编码和解码,适用于处理大量数据而无需一次性将其全部加载到内存中。

TextEncoderStream
const encoder = new TextEncoderStream(); const stream = new ReadableStream({ start(controller) { controller.enqueue('Hello'); controller.enqueue('World'); controller.close(); }, }); const reader = stream.pipeThrough(encoder).getReader(); reader.read().then(({ done, value }) => { console.log(value); // Uint8Array [72, 101, 108, 108, 111] });

Streams API

原生平台现已全局支持标准 Web 流,以匹配 Web 和服务器平台上的行为。有关 Web 和 Node.js 的具体支持情况,请参阅浏览器和服务器运行时支持。EAS Hosting 服务器运行时也支持标准 Web Streams API。

全局访问 ReadableStream、WritableStream 和 TransformStream 类。

ReadableStream
const stream = new ReadableStream({ start(controller) { controller.enqueue('Hello'); controller.enqueue('World'); controller.close(); }, }); const reader = stream.getReader(); reader.read().then(({ done, value }) => { console.log(value); // Hello }); reader.read().then(({ done, value }) => { console.log(value); // World });

URL API

URL 在所有平台上均提供标准 API。

在原生平台上,内置的 URL 和 URLSearchParams 实现会取代 react-native 中的 shim。有关 Web 和 Node.js 的支持情况,请参阅浏览器和服务器运行时支持。

URL and URLSearchParams
const url = new URL('https://expo.dev'); const params = new URLSearchParams();

Expo 内置的 URL 支持力求完全符合规范。唯一的例外是,原生平台目前不支持主机名中的非 ASCII 字符。

Non-ASCII characters
console.log(new URL('http://🥓').toString()); // This outputs the following: // - Web, Node.js: http://xn--pr9h/ // - Android, iOS: http://🥓/

structuredClone

structuredClone 是一个内置函数,可用于创建值的深拷贝,包括 Map、Set 和 ArrayBuffer 等复杂对象。它在所有平台上均可用。

const original = { name: 'Expo', date: new Date() }; const clone = structuredClone(original); console.log(clone); // { name: 'Expo', date: Date }

尚未实现 ArrayBuffer 和 TypedArray 的 transfer 选项。

请移除为 structuredClone 添加的自定义 polyfill,以避免增加冗余。有关详细信息,请参阅结构化克隆算法的标准文档。

Constants

Platform

Android
iOS
tvOS
Web

Type: { canUseEventListeners: boolean, canUseViewport: boolean, isAsyncDebugging: boolean, isDOMAvailable: boolean, OS: string, select: PlatformSelect }

SharedRef

Android
iOS
tvOS
Web

Type: SharedRef

uuid

Android
iOS
tvOS
Web

Type: UUID

Hooks

useEvent(eventEmitter, eventName, initialValue)

Android
iOS
tvOS
Web
ParameterTypeDescription
eventEmitterEventEmitter<TEventsMap>

An object that emits events. For example, a native module or shared object or an instance of EventEmitter.

eventNameTEventName

Name of the event to listen to.

initialValue(optional)TInitialValue | null

An event parameter to use until the event is called for the first time.

Default:null

React hook that listens to events emitted by the given object. The returned value is an event parameter that gets updated whenever a new event is dispatched.

Returns:
InferEventParameter<TEventListener, TInitialValue>

A parameter of the event listener.

Example

import { useEvent } from 'expo'; import { VideoPlayer } from 'expo-video'; export function PlayerStatus({ videoPlayer }: { videoPlayer: VideoPlayer }) { const { status } = useEvent(videoPlayer, 'statusChange', { status: videoPlayer.status }); return <Text>{`Player status: ${status}`}</Text>; }

useEventListener(eventEmitter, eventName, listener)

Android
iOS
tvOS
Web
ParameterTypeDescription
eventEmitterEventEmitter<TEventsMap>

An object that emits events. For example, a native module or shared object or an instance of EventEmitter.

eventNameTEventName

Name of the event to listen to.

listenerTEventListener

A function to call when the event is dispatched.


React hook that listens to events emitted by the given object and calls the listener function whenever a new event is dispatched. The event listener is automatically added during the first render and removed when the component unmounts.

Returns:
void

Example

import { useEventListener } from 'expo'; import { useVideoPlayer, VideoView } from 'expo-video'; export function VideoPlayerView() { const player = useVideoPlayer(videoSource); useEventListener(player, 'playingChange', ({ isPlaying }) => { console.log('Player is playing:', isPlaying); }); return <VideoView player={player} />; }

useReleasingSharedObject(factory, dependencies)

Android
iOS
tvOS
Web
ParameterType
factory() => TSharedObject
dependenciesDependencyList

Returns a shared object, which is automatically cleaned up when the component is unmounted.

Returns:
TSharedObject

useReleasingSharedObjectWithLifecycle(lifecycle, dependencies)

Android
iOS
tvOS
Web
ParameterType
lifecycleReleasingSharedObjectLifecycle<TSharedObject>
dependenciesDependencyList

Returns a shared object, delegating dependency changes to lifecycle callbacks.

Returns:
TSharedObject

Classes

CodedError

Android
iOS
tvOS
Web

Type: Class extends Error

A general error class that should be used for all errors in Expo modules. Guarantees a code field that can be used to differentiate between different types of errors without further subclassing Error.

CodedError Properties

code

Android
iOS
tvOS
Web
Type: string

info

Android
iOS
tvOS
Web
Optional • Type: any

UnavailabilityError

Android
iOS
tvOS
Web

Type: Class extends CodedError

A class for errors to be thrown when a property is accessed which is unavailable, unsupported, or not currently implemented on the running platform.

UnavailabilityError Properties

code

Android
iOS
tvOS
Web
Type: string

info

Android
iOS
tvOS
Web
Optional • Type: any

EventEmitterType

Android
iOS
tvOS
Web

A class that provides a consistent API for emitting and listening to events. It shares many concepts with other emitter APIs, such as Node's EventEmitter and fbemitter. When the event is emitted, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and discarded. Its implementation is written in C++ and common for all the platforms.

EventEmitterType Methods

addListener(eventName, listener)

Android
iOS
tvOS
Web
ParameterType
eventNameEventName
listenerTEventsMap[EventName]

Adds a listener for the given event name.

Returns:
EventSubscription

emit(eventName, ...args)

Android
iOS
tvOS
Web
ParameterType
eventNameEventName
...argsParameters<TEventsMap[EventName]>

Synchronously calls all the listeners attached to that specific event. The event can include any number of arguments that will be passed to the listeners.

Returns:
void

listenerCount(eventName)

Android
iOS
tvOS
Web
ParameterType
eventNameEventName

Returns a number of listeners added to the given event.

Returns:
number

removeAllListeners(eventName)

Android
iOS
tvOS
Web
ParameterType
eventNamekeyof TEventsMap

Removes all listeners for the given event name.

Returns:
void

removeListener(eventName, listener)

Android
iOS
tvOS
Web
ParameterType
eventNameEventName
listenerTEventsMap[EventName]

Removes a listener for the given event name.

Returns:
void

startObserving(eventName)

Android
iOS
tvOS
Web
ParameterType
eventNameEventName

Function that is automatically invoked when the first listener for an event with the given name is added. Override it in a subclass to perform some additional setup once the event started being observed.

Returns:
void

stopObserving(eventName)

Android
iOS
tvOS
Web
ParameterType
eventNameEventName

Function that is automatically invoked when the last listener for an event with the given name is removed. Override it in a subclass to perform some additional cleanup once the event is no longer observed.

Returns:
void

NativeModuleType

Android
iOS
tvOS
Web

Type: Class extends EventEmitter<TEventsMap>

A class for all native modules. Extends the EventEmitter class.

SharedObjectType

Android
iOS
tvOS
Web

Type: Class extends EventEmitter<TEventsMap> implements EventEmitter<TEventsMap>

Base class for all shared objects that extends the EventEmitter class. The implementation is written in C++, installed through JSI and common for mobile platforms.

SharedObjectType Methods

release()

Android
iOS
tvOS
Web

A function that detaches the JS and native objects to let the native object deallocate before the JS object gets deallocated by the JS garbage collector. Any subsequent calls to native functions of the object will throw an error as it is no longer associated with its native counterpart.

In most cases, you should never need to use this function, except some specific performance-critical cases when manual memory management makes sense and the native object is known to exclusively retain some native memory (such as binary data or image bitmap). Before calling this function, you should ensure that nothing else will use this object later on. Shared objects created by React hooks are usually automatically released in the effect's cleanup phase, for example: useVideoPlayer() from expo-video and useImage() from expo-image.

Returns:
void

SharedRefType

Android
iOS
tvOS
Web

Type: Class extends SharedObject<TEventsMap> implements SharedObject<TEventsMap>

A SharedObject that holds a reference to any native object. Allows passing references to native instances among different independent libraries.

For instance, ImageRef from expo-image references a Drawable on Android and an UIImage on iOS. Since both types are common on these platforms, different native modules can use them without depending on each other. In particular, this enables the expo-image-manipulator to pass the resulted image directly to the image view from expo-image without any additional writes and reads from the file system.

SharedRefType Properties

nativeRefType

Android
iOS
tvOS
Web
Type: string

The type of the native reference.

Methods

createPermissionHook(methods)

Android
iOS
tvOS
Web
ParameterType
methodsPermissionHookMethods<Permission, Options>

Create a new permission hook with the permission methods built-in. This can be used to quickly create specific permission hooks in every module.

Returns:
(options: PermissionHookOptions<Options>) => [Permission | null, RequestPermissionMethod<Permission>, GetPermissionMethod<Permission>]

createSnapshotFriendlyRef()

Android
iOS
tvOS
Web

Create a React ref object that is friendly for snapshots. It will be represented as [React.ref] in snapshots.

Returns:
RefObject<T | null>

A React ref object.

installOnUIRuntime(uiRuntimeHolder)

Android
iOS
tvOS
Web
ParameterTypeDescription
uiRuntimeHolderobject

The UI runtime holder from getUIRuntimeHolder() in react-native-worklets.


Installs Expo Modules on the UI worklet runtime so worklet callbacks and serializable SharedObjects work there.

Returns:
void

isRunningInExpoGo()

Android
iOS
tvOS
Web

Returns a boolean value whether the app is running in Expo Go.

Returns:
boolean

registerRootComponent(component)

Android
iOS
tvOS
Web
ParameterTypeDescription
componentComponentType<P>

The React component class that renders the rest of your app.


Sets the initial React component to render natively in the app's root React Native view on Android, iOS, tvOS and the web.

This method does the following:

  • Invokes React Native's AppRegistry.registerComponent.
  • Invokes React Native web's AppRegistry.runApplication on web to render to the root index.html file.
  • Polyfills the process.nextTick function globally.

This method also adds the following dev-only features that are removed in production bundles.

  • Adds the Fast Refresh and bundle splitting indicator to the app.
  • Asserts if the expo-updates package is misconfigured.
  • Asserts if react-native is not aliased to react-native-web when running in the browser.
Returns:
void

registerWebModule(moduleImplementation, moduleName)

Android
iOS
tvOS
Web
ParameterTypeDescription
moduleImplementationModuleType

A class that extends NativeModule. The class is registered under globalThis.expo.modules[className].

moduleNamestring

A name to register the module under globalThis.expo.modules[className].


Registers a web module.

Returns:
InstanceType<ModuleType>

A singleton instance of the class passed into arguments.

reloadAppAsync(reason)

Android
iOS
tvOS
Web
ParameterTypeDescription
reason(optional)string

The reason for reloading the app. This is used only for some platforms.

Default:'Reloaded from JS call'

Reloads the app. This method works for both release and debug builds.

Unlike Updates.reloadAsync(), this function does not use a new update even if one is available. It only reloads the app using the same JavaScript bundle that is currently running.

Returns:
Promise<void>

requireNativeModule(moduleName)

Android
iOS
tvOS
Web
ParameterTypeDescription
moduleNamestring

Name of the requested native module.


Imports the native module registered with given name. In the first place it tries to load the module installed through the JSI host object and then falls back to the bridge proxy module. Notice that the modules loaded from the proxy may not support some features like synchronous functions.

Returns:
ModuleType

Object representing the native module.

requireNativeView(moduleName, viewName)

Android
iOS
tvOS
Web
ParameterType
moduleNamestring
viewName(optional)string

A drop-in replacement for requireNativeComponent.

Returns:
ComponentType<P>

requireOptionalNativeModule(moduleName)

Android
iOS
tvOS
Web
ParameterTypeDescription
moduleNamestring

Name of the requested native module.


Imports the native module registered with the given name. The same as requireNativeModule, but returns null when the module cannot be found instead of throwing an error.

Returns:
ModuleType | null

Object representing the native module or null when it cannot be found.

Event subscriptions

useEventListener(eventEmitter, eventName, listener)

Android
iOS
tvOS
Web
ParameterTypeDescription
eventEmitterEventEmitter<TEventsMap>

An object that emits events. For example, a native module or shared object or an instance of EventEmitter.

eventNameTEventName

Name of the event to listen to.

listenerTEventListener

A function to call when the event is dispatched.


React hook that listens to events emitted by the given object and calls the listener function whenever a new event is dispatched. The event listener is automatically added during the first render and removed when the component unmounts.

Returns:
void

Example

import { useEventListener } from 'expo'; import { useVideoPlayer, VideoView } from 'expo-video'; export function VideoPlayerView() { const player = useVideoPlayer(videoSource); useEventListener(player, 'playingChange', ({ isPlaying }) => { console.log('Player is playing:', isPlaying); }); return <VideoView player={player} />; }

Interfaces

EventSubscription

Android
iOS
tvOS
Web

A subscription object that allows to conveniently remove an event listener from the emitter.

EventSubscription Methods

remove()

Android
iOS
tvOS
Web

Removes an event listener for which the subscription has been created. After calling this function, the listener will no longer receive any events from the emitter.

Returns:
void

Types

EventEmitter

Android
iOS
tvOS
Web

Type: ExpoEventEmitter<TEventsMap>

FloatBasedTypedArray

Android
iOS
tvOS
Web

Literal type: union

A union type for all floating point based TypedArray objects.

Acceptable values are: Float32Array | Float64Array

IntBasedTypedArray

Android
iOS
tvOS
Web

Literal type: union

A union type for all integer based TypedArray objects.

Acceptable values are: Int8Array | Int16Array | Int32Array

PermissionExpiration

Android
iOS
tvOS
Web

Literal type: union

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never' | number

PermissionHookOptions

Android
iOS
tvOS
Web

Literal type: union

Acceptable values are: PermissionHookBehavior | Options

PermissionResponse

Android
iOS
tvOS
Web

An object obtained by permissions get and request functions.

PropertyTypeDescription
canAskAgainboolean

Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.

ReleasingSharedObjectLifecycle

Android
iOS
tvOS
Web
PropertyTypeDescription
factory() => TSharedObject

Creates the shared object when the hook initializes or when shouldRecreate returns true.

release(optional)(object: TSharedObject) => void

Releases an object after it has been replaced or when the component unmounts. When omitted, the object's release method is called.

shouldRecreate(optional)(object: TSharedObject, context: ReleasingSharedObjectLifecycleContext) => boolean

Called during render when dependencies change to decide whether to replace the object. Return false to keep the current object and handle the dependency change with the update function. When omitted or true, dependency changes recreate the object, matching useReleasingSharedObject.

Must be a pure function with no side effects — it is called during the render phase and React may invoke it more than once with the same inputs.

update(optional)(object: TSharedObject, context: ReleasingSharedObjectLifecycleContext) => void | Promise<void>

Called after commit when dependencies changed and shouldRecreate returned false. Has no effect unless shouldRecreate is provided and returns false for the changed dependencies.

If the returned Promise rejects, the error is logged with console.error. Handle errors inside update if specific error handling is needed.

If a subsequent dependency change or unmount requires the object to be released while an async update is still in-flight, the release is deferred until the update settles.

ReleasingSharedObjectLifecycleContext

Android
iOS
tvOS
Web
PropertyTypeDescription
dependenciesDependencyList

The dependency values from the current render.

previousDependenciesDependencyList

The dependency values from the last committed object lifecycle decision.

TypedArray

Android
iOS
tvOS
Web

Literal type: union

A TypedArray describes an array-like view of an underlying binary data buffer.

Acceptable values are: IntBasedTypedArray | UintBasedTypedArray | FloatBasedTypedArray

UintBasedTypedArray

Android
iOS
tvOS
Web

Literal type: union

A union type for all unsigned integer based TypedArray objects.

Acceptable values are: Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array

Enums

PermissionStatus

Android
iOS
tvOS
Web

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.

常见问题

关于在项目中使用 expo 包的一些常见问题。

rootRegisterComponent setup for existing React Native projects

如果你手动管理 React Native 项目的原生目录(android 和 ios),则需要按照以下说明设置 registerRootComponent 函数。这是 Expo 模块正常工作的必要条件。

Android

更新 android/app/src/main/your-package/MainActivity.java 文件,在 getMainComponentName 函数中使用名称 main。

android/app/src/main/your-package/MainActivity.java
@Override protected String getMainComponentName() { + return "main"; }

iOS

更新 iOS ios/your-project/AppDelegate.(m|mm|swift) 文件,在 application:didFinishLaunchingWithOptions: 函数的 createRootViewWithBridge:bridge moduleName:@"main" initialProperties:initProps 行中使用 moduleName main。

如果我想将主应用文件命名为 App.js 或 app/_layout.tsx 以外的名称,该怎么办?

对于不使用 Expo Router 的项目,你可以将 package.json 中的 "main" 设置为项目中的任意文件。如果这样做,则需要使用 registerRootComponent。如果使用自定义入口文件,export default 不会将此组件设为应用的根组件。

例如,假设你想将 src/main.jsx 设为应用的入口文件——也许你不喜欢在项目根目录中放置 JavaScript 文件。首先,在 package.json 中进行如下设置:

package.json
{ "main": "src/main.jsx" }

然后,在 src/main.jsx 中,确保调用 registerRootComponent,并传入你希望在应用根目录处渲染的组件:

src/main.jsx
import { registerRootComponent } from 'expo'; import { View } from 'react-native'; function App() { return <View />; } registerRootComponent(App);

对于使用 Expo Router 的项目,你可以按照 Expo Router 安装指南中的步骤创建自定义入口点。若要在 Expo Router 项目中使用顶层 src 目录,请参阅 src 目录参考了解更多信息。