[英]How to call Javascript function from Kotlin code?
我正在嘗試將Kotlin代碼編譯為Javascript。 在我的代碼中,我需要將字符串編碼為URI。 我的兩個變體都是編譯失敗:
class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
return encodeURIComponent(str)
}
在此代碼中,編譯器無法找到函數encodeURIComponent(str),根據所有瀏覽器都支持https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp 。
替代方案:
class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
return URLEncoder.encode(str, Charsets.UTF_8.name())
}
找不到Java類URLEncoder(與Java中一樣導入文件中)。 當為JVM而不是JS編譯時,這有效。
我還用以下標記了Kotlin模塊:
compileKotlin2Js.kotlinOptions.moduleKind = "umd"
我發現在Kotlin中聲明Javascript函數的最新方法是:
external fun encodeURIComponent(str: String): String
一旦將其添加到Kotlin類中,所有內容都將毫無問題地進行編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.