JetBrains宣布Jetpack Compose for Web,使用Kotlin開發(fā)適配多端的Web UI

粉絲福利:小編會從今天留言的小伙伴中隨機抽贈送8.88元現(xiàn)金紅包。
娛樂抽獎,大家隨緣積極參與啦,給生活一點小幸運~感謝大家的支持
文 | 局長
出品 | OSC開源社區(qū)(ID:oschina2013)
Jetpack Compose 是用于構(gòu)建原生界面的新款 Android 工具包。它可簡化并加快 Android 上的界面開發(fā)。使用更少的代碼、強大的工具和直觀的 Kotlin API,快速讓應(yīng)用生動而精彩。UI 代碼和預(yù)覽如下圖所示:
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
使用 Compose for Web 構(gòu)建用戶界面
借助 Compose for Web,開發(fā)者通過使用 Kotlin 并應(yīng)用 Jetpack Compose 的概念和 API 為 Web 構(gòu)建響應(yīng)式用戶界面,以表達應(yīng)用程序的狀態(tài)、行為和邏輯。
可組合的 DOM API
通過 DOM 元素和 HTML 標(biāo)簽表達設(shè)計和布局
使用類型安全的 HTML DSL 構(gòu)建 UI 表示形式
通過使用類型安全的 CSS DSL 創(chuàng)建樣式表來完全控制應(yīng)用程序的外觀
通過 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 機制來提供特定于平臺的實現(xiàn),從而使用和構(gòu)建可在 Android、桌面和 Web 上運行的 Compose 小部件
處于實驗性階段的一組布局原語 (layout primitives) 和API,這些原語和 API 與 Compose for Desktop/Android 的功能相似
示例代碼
使用 Composable DOM 編寫簡單的計數(shù)器
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))
}
}
@Composable
fun 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 */
}
}
@Composable
fun MyComponent() {
Div(attrs = {
classes(MyStyleSheet.container)
}) {
Span(attrs = {
classes(MyStyleSheet.content)
}) {
Text("Hello world!")
}
}
}
往 期 推 薦
1、Intellij IDEA這樣 配置注釋模板,讓你瞬間高出一個逼格! 2、基于SpringBoot的迷你商城系統(tǒng),附源碼! 3、最牛逼的 Java 日志框架,性能無敵,橫掃所有對手! 4、把Redis當(dāng)作隊列來用,真的合適嗎? 5、驚呆了,Spring Boot居然這么耗內(nèi)存!你知道嗎? 6、全網(wǎng)最全 Java 日志框架適配方案!還有誰不會? 7、Spring中毒太深,離開Spring我居然連最基本的接口都不會寫了

點分享

點收藏

點點贊

點在看
評論
圖片
表情


