npm i --save @nativescript/jetpack-compose
- 版本: 1.0.0-beta.0
- GitHub: https://github.com/NativeScript/plugins
- NPM: https://npmjs.net.cn/package/%40nativescript%2Fjetpack-compose
- 下载
- 昨天: 0
- 上周: 0
- 上个月: 0
@nativescript/jetpack-compose
NativeScript 的 Jetpack Compose
npm install @nativescript/jetpack-compose
用法
调整 App_Resources/Android/app.gradle
以包含您所需的 Jetpack Compose 版本和依赖项
dependencies {
def compose_version = "1.2.1"
implementation "androidx.compose.ui:ui:$compose_version"
// Tooling support (Previews, etc.)
implementation "androidx.compose.ui:ui-tooling:$compose_version"
// Add any other dependencies your Jetpack Compose UI needs
}
android {
// other settings like targetSdk, etc.
buildFeatures {
compose true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
composeOptions {
kotlinCompilerExtensionVersion '1.3.2'
}
}
创建一个 Compose 视图
您可以在 App_Resources 中创建任何 Kotlin 文件,例如
App_Resources/Android/src/main/java/BasicView.kt
class BasicView {
data class ExampleUIState(
val text: String = ""
) {}
class ExampleViewModel(
) : ViewModel() {
var uiState by mutableStateOf(ExampleUIState())
}
var mViewModel = ExampleViewModel()
fun generateComposeView(view: ComposeView): ComposeView {
return view.apply {
setContent {
MaterialTheme {
val uiState = mViewModel.uiState;
Text(uiState.text)
}
}
}
}
fun updateData(value: Map<Any, Any>) {
val v = value["data"] as String;
onEvent?.invoke(v)
mViewModel.uiState = ExampleUIState(v);
}
var onEvent: ((String) -> Unit)? = null
}
注册您的 Compose 视图
这可以在引导文件(通常是 app.ts
或 main.ts
)中完成,甚至可以在需要它的视图组件中完成。
app.ts
import { registerJetpackCompose, ComposeDataDriver } from '@nativescript/jetpack-compose';
// A. You can generate types for your own Compose Provider with 'ns typings android --aar {path/to/{name}.aar}'
// B. Otherwise you can ignore by declaring the package resolution path you know you provided
declare var com;
registerJetpackCompose('flyingHearts', (view) => new ComposeDataDriver(new com.example.FlyingHearts(), view));
使用 Compose 视图与任何 NativeScript 布局
这展示了通常所说的“纯” NativeScript 应用。然而,您可以使用此插件与任何风味(Angular、React、Svelte、Vue 等)配合使用。
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" class="page" xmlns:jc="@nativescript/jetpack-compose">
<StackLayout>
<jc:JetpackCompose composeId="flyingHearts" composeEvent="{{ onEvent }}" data="{{ text }}"/>
</StackLayout>
</Page>
与 Angular 一起使用
import { registerElement } from '@nativescript/angular'
import { JetpackCompose } from '@nativescript/jetpack-compose'
registerElement('JetpackCompose', () => JetpackCompose)
现在它可以在任何 Angular 组件中使用,例如
<StackLayout>
<JetpackCompose composeId="flyingHearts" (composeEvent)="onEvent($event)" [data]="data"></JetpackCompose>
</StackLayout>
鸣谢
NativeScript 由 Valor Software 作为官方合作伙伴大力支持。我们自豪地提供指导、咨询和开发协助,涵盖所有 NativeScript 事宜。
许可证
MIT