You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin React中RBuilder与RDOMBuilder的区别是什么?

Difference Between RBuilder and RDOMBuilder<*> in Kotlin React

Great question—this is a super common point of confusion when you’re getting up to speed with Kotlin React’s DSL. Let’s break down the two clearly with examples so you know exactly when to use each.

What is RBuilder?

RBuilder is your top-level or component-level context for building React component trees. Think of it as the canvas where you define entire components or reusable chunks of UI that can be dropped into any part of your app.

When you write a function like fun RBuilder.someComponent(), you’re creating a standalone reusable component. You can call this function from any other RBuilder context (like your root App component) to insert its entire UI tree into the parent.

Example:

// Defining a reusable component with RBuilder
fun RBuilder.userProfile() {
    div {
        img { attrs.src = "/avatar.png" }
        h3 { +"John Doe" }
        p { +"Software Developer" }
    }
}

// Using it in your app
fun RBuilder.App() {
    div {
        userProfile() // Drop the entire profile component here
        p { +"Welcome to our platform!" }
    }
}

What is RDOMBuilder<*>?

RDOMBuilder<*> is a per-DOM-element context. It’s the receiver you get inside the lambda of a specific DOM element (like div { ... }, button { ... }). This builder lets you configure that specific element’s properties, events, styles, and add child content to it.

A function like fun RDOMBuilder<*>.someComponent() is an extension that only works inside an existing DOM element’s scope. It’s useful for reusing logic that modifies or adds content to a specific kind of DOM node.

Example:

// Defining an extension for DOM elements with RDOMBuilder
fun RDOMBuilder<HTMLDivElement>.addCardStyles() {
    attrs.style {
        padding = 16.px
        borderRadius = 8.px
        boxShadow = Shadow(0, 2, 4, Color.gray)
    }
    // You can also add child elements here
    div { +"This is inside a styled card" }
}

// Using it on a specific div
fun RBuilder.App() {
    div {
        addCardStyles() // Applies styles and adds content to THIS div
        p { +"Other content in the card" }
    }
}

Core Differences at a Glance

  • Context Scope: RBuilder is for building entire components or UI fragments; RDOMBuilder<*> is for modifying or extending a single DOM element.
  • Reuse Style: RBuilder extensions are standalone components you can place anywhere; RDOMBuilder<*> extensions are tied to a specific DOM element’s lambda.
  • Capabilities: RBuilder lets you create multiple elements/components; RDOMBuilder<*> lets you tweak the target element’s attrs, events, styles, plus add children to it.

内容的提问来源于stack exchange,提问作者deviant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:40:34