javascript - 使用内容创建 Kotlin/JS WebComponent

标签 javascript html kotlin web-component kotlin-multiplatform

我要create a custom tag with Kotlin包含默认内容。链接的示例工作正常,但我没有设法将一些默认内容(例如输入元素)添加到自定义标签。

我尝试了不同的方法,但到目前为止,我只设法将输入元素添加到 DOM 中的自定义标签旁边,而不是在其中。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Client</title>
</head>
<body>
<script src="webcomponentexampleproject.js"></script>
<div id="root"></div>
</body>
</html>

client.kt

import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.html.InputType
import kotlinx.html.dom.append
import kotlinx.html.dom.create

fun main() {
    window.onload = {

        document.getElementById("root")!!.append {
            webcomponent {
                text = "added it"
                +"some more text"
            }
        }

    }
}

WebComponent.kt

import kotlinx.html.*
import kotlinx.html.js.onChangeFunction
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event
import kotlin.properties.Delegates

@JsExport
class WebComponent(consumer: TagConsumer<*>, _text: String = "", _backgroundColor: String = "none") :
    HTMLTag("webcomponent", consumer, emptyMap(), inlineTag = true, emptyTag = false), HtmlInlineTag {

    var text: String by Delegates.observable(_text) { prop, old, new ->
        el.value = text
    }
    var backgroundColor: String by Delegates.observable(_backgroundColor) { prop, old, new ->
        el.style.backgroundColor = backgroundColor
    }

    private val el: HTMLInputElement

    init {
        //TODO: this input element should be INSIDE the tag
        el = consumer.input {
            type = InputType.text
            value = this@WebComponent.text
        }.unsafeCast<HTMLInputElement>()
    }
}

// make the new custom tag usable via the kotlinx.html DSL
fun <T> TagConsumer<T>.webcomponent(block: WebComponent.() -> Unit = {}): T {
    return WebComponent(this).visitAndFinalize(this, block)
}

最佳答案

尝试在元素初始化之后调用onTagContentUnsafe:

private val el: HTMLInputElement

init {
    el = consumer.input {
        type = InputType.text
        value = this@WebComponent.text
    }.unsafeCast<HTMLInputElement>()

    consumer.onTagContentUnsafe {
        +el.outerHTML
    }
}

关于javascript - 使用内容创建 Kotlin/JS WebComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67031836/

相关文章:

javascript - jQuery 输入 ReplaceWith() 选择并记住在重新加载时选择

javascript - 使用 YUIcompressor 压缩多个 JavaScript 文件?

javascript - 5 星

html - 如何在 nginx 中提供 html 文件而不显示此别名设置中的扩展名

kotlin - 在 Kotlin 协程中收集多个异步结果,忽略超时异常

java - 在 kotlin 中添加 2 个或更多构造函数

javascript - 星级评定是让星星从后面填满

javascript - JQuery:以隐藏方式启动 slideToggle()

html - 绝对定位的 div 不起作用

android-intent - Kotlin 可打包类抛出 ClassNotFoundException