Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Kotlinx.html为按钮创建onClick函数?_Html_Kotlin_Ktor_Kotlinx_Kotlinx Html - Fatal编程技术网

如何使用Kotlinx.html为按钮创建onClick函数?

如何使用Kotlinx.html为按钮创建onClick函数?,html,kotlin,ktor,kotlinx,kotlinx-html,Html,Kotlin,Ktor,Kotlinx,Kotlinx Html,我正在使用Kotlin的html库kotlinx.html进行动态html构建 我想创建一个按钮,当点击时触发一个函数。这是我当前的代码: class TempStackOverflow(): Template<FlowContent> { var counter: Int = 1 override fun FlowContent.apply() { div { button(type = ButtonType.button)

我正在使用Kotlin的html库kotlinx.html进行动态html构建

我想创建一个按钮,当点击时触发一个函数。这是我当前的代码:

class TempStackOverflow(): Template<FlowContent> {
    var counter: Int = 1

    override fun FlowContent.apply() {
        div {
            button(type = ButtonType.button) {
                onClick = "${clicked()}"
            }
        }
    }

    fun clicked() {
        counter++
    }
}

我尝试了几次批准,并搜索了一个解决方案,但没有找到合适的文档。

不幸的是,您完全没有理解kotlinx.html库的要点。它只能为您呈现HTML,不应该是动态的kotlin->JSBridge,比如Vaadin或GWT。所以,您只需将
单击的
函数转换为字符串的结果设置为
onClick
按钮的属性,这是有效的
kotlin.Unit
,因为如果您不直接指定另一种类型,
kotlin.Unit
是函数的默认返回值

    fun clicked() {
        counter++
    }

    fun clicked():Unit {
        counter++
    }

    fun clicked():Kotlin.Unit {
        counter++
    }

因此,当您将“${clicked()}”设置为某个属性时,它实际上执行了一个函数(这里的计数器递增)并返回Koltin.Unit值,当它在“${}”模板中呈现时,它将变成“Kotlin.Unit”字符串

感谢您的快速回答!我正在拼命地为我的应用程序寻找一个平台,所以我有点匆忙地使用它。谢谢你启发我。我将尝试使用Kotlin+JS/React。我目前正在其他项目中与React合作,我应该提供我需要的。非常好的选择,Kotlin用于后端,JS/React用于前端是一个明智的决定
    fun clicked():Unit {
        counter++
    }
    fun clicked():Kotlin.Unit {
        counter++
    }