javascript - 创建一个包含内容的 Kotlin/JS WebComponent
问题描述
我想用 Kotlin 创建一个包含默认内容的自定义标签。链接的示例工作正常,但我没有设法将一些默认内容(例如输入元素)添加到自定义标签。
我尝试了不同的方法,但到目前为止,我只设法在 DOM 中的自定义标签旁边添加了输入元素,但没有在其中添加。
索引.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>
客户端.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"
}
}
}
}
Web组件.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)
}
解决方案
推荐阅读
- java - Jboss eap 7.0 无法部署 .war 文件并一次又一次地重新启动部署
- android - 如何在没有 NDK 的情况下使用 USB 网络摄像头?
- regex - 正则表达式:在 string1 和 string2 之间提取字符串,而 string2 可以是多个字符串之一
- vue.js - Vue关闭组件返回避免直接改变道具
- java - 图像左右移动
- python - Python DataFrame - 删除列值属于值列表的行
- javascript - 在 JavaScript 中计算小数点后的数字
- mysql - 具有相同行数但具有更多列的第二个表包含更多数据的两个相同表上的相同索引是否会影响查找?
- python - 在 python 中,对象和类属性也可以在类定义之外定义,这是一种不好的编码习惯吗?
- javascript - 脚本未在 React JS 中执行