This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 57).
useNativeState
一个 React Hook,用于创建可在 JavaScript 与原生 SwiftUI 视图之间共享的可观察状态。
useNativeState 返回一个 ObservableState,它在原生端映射到 SwiftUI 的 ObservableObject,因此对 .value 的读取和写入会被 SwiftUI 直接观察到,而不会经过 React 的渲染周期。这使你可以在 UI 线程上的 worklet 中同步更新原生视图。
安装
If you are installing this in an existing React Native app, make sure to install expo in your project.
用法
注意: 使用 worklet 需要在项目中安装
react-native-worklets。useNativeState本身无需安装它即可使用,但下方展示的 UI 线程同步更新依赖 worklet 运行时。
以下示例会在用户输入时对电话号码进行格式化。格式化以及对 maskedPhone.value(文本)和 selection.value(光标位置)的写入都会在 UI 线程上同步进行,因此原始输入与格式化后的值之间不会出现闪烁。
API
import { useNativeState } from '@expo/ui/swift-ui';
Hooks
Creates an observable native state that is automatically cleaned up when the
component unmounts. initialValue is captured once on the first render
ObservableState<T>Types
Observable state shared between JavaScript and native views (Jetpack Compose on Android and SwiftUI on iOS).
Type: SharedObject extended by: