gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:02:04 26 4
gpt4 key购买 nike

我要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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com