看到一款基于多端的 UI 调试工具,一套代码适应多端,真的是太棒了,上面分享给大家。
1、前言
该工具是赫赫有名的 JetBrains 公司新推出的,名曰:“Jetpack Compose for Web”,官网介绍称此我的项目基于 Google 古代 UI 工具包 Jetpack Compose,反对应用 Kotlin 编写响应式 Web UI。
Jetpack Compose 是用于构建原生界面的新款 Android 工具包。它可简化并放慢 Android 上的界面开发。应用更少的代码、弱小的工具和直观的 Kotlin API,疾速让利用活泼而精彩。
UI 代码和预览如下图所示:
据介绍,Jetpack Compose for Web 可简化并减速 Web 利用的 UI 开发,指标是在 Web、桌面和 Android APP 之间实现 UI 代码共享,一套代码适应多端。目前处于技术预览阶段。
fun greet() = listOf("Hello", "Hallo", "Hola", "Servus").random()
renderComposable("greetingContainer") {
var greeting by remember { mutableStateOf(greet()) }Button(attrs = { onClick { greeting = greet() } }) { Text(greeting)}
}
Result: Servus
2、应用 Compose for Web 构建用户界面
借助 Compose for Web,开发者通过应用 Kotlin 并利用 Jetpack Compose 的概念和 API 为 Web 构建响应式用户界面,以表白应用程序的状态、行为和逻辑。
可组合的 DOM API
- 通过 DOM 元素和 HTML 标签表白设计和布局
- 应用类型平安的 HTML DSL 构建 UI 示意模式
- 通过应用类型平安的 CSS DSL 创立样式表来齐全控制应用程序的外观
通过 DOM 子树与其余 JavaScript 库集成
fun main() { renderComposable("root") { var platform by remember { mutableStateOf("a platform") } P { Text("Welcome to Compose for $platform! ") Button(attrs = { onClick { platform = "Web" } }) { Text("...for what?") } } A("https://www.jetbrains.com/lp/compose-web") { Text("Learn more!") } }}
具备 Web 反对的多平台小部件- 通过利用 Kotlin 的 Expect-actual 机制来提供特定于平台的实现,从而应用和构建可在 Android、桌面和 Web 上运行的 Compose 小部件
- 处于实验性阶段的一组布局原语 (layout primitives) 和API,这些原语和 API 与 Compose for Desktop/Android 的性能类似
3、示例代码
应用 Composable DOM 编写简略的计数器
fun main() { val count = mutableStateOf(0) renderComposable(rootElementId = "root") { Button(attrs = { onClick { count.value = count.value - 1 } }) { Text("-") } Span(style = { padding(15.px) }) { /* we use inline style here */ Text("${count.value}") } Button(attrs = { onClick { count.value = count.value + 1 } }) { Text("+") } }}
申明和应用样式表
object MyStyleSheet : StyleSheet() { val container by style { /* define a class `container` */ border(1.px, LineStyle.Solid, Color.RGB(255, 0, 0)) }}@Composablefun MyComponent() { Div(attrs = { classes(MyStyleSheet.container) /* use `container` class */ }) { Text("Hello world!") }}fun main() { renderComposable(rootElementId = "root") { Style(MyStyleSheet) /* mount the stylesheet */ MyComponent() }}
申明和应用 CSS 变量
object MyVariables : CSSVariables { val contentBackgroundColor by variable<Color>() /* declare a variable */}object MyStyleSheet: StyleSheet() { val container by style { MyVariables.contentBackgroundColor(Color("blue")) /* set its value */ } val content by style { backgroundColor(MyVariables.contentBackgroundColor.value()) /* use it */ }}@Composablefun MyComponent() { Div(attrs = { classes(MyStyleSheet.container) }) { Span(attrs = { classes(MyStyleSheet.content) }) { Text("Hello world!") } }}
起源 | 程序员编程