如何使用SVG与kotlin反应

pal*_*jir 4 kotlin reactjs

您好,有人可以帮助我如何使用SVG与Kotlin React.

我想使用react和javascript实现与以下示例类似的事情:

const MyComponent = ({radius, color}) => (
  <svg width={radius * 2} height={radius * 2}>
    <circle cx={radius} cy={radius} r={radius} fill=  {color}/>
  </svg>
)
Run Code Online (Sandbox Code Playgroud)

不幸的是,我自己找不到任何示例或足够的文档.

使用Kotlin我不知道我可以用什么语言来实现同样的功能.任何人都可以帮我用Kotlin填写以下片段吗?

fun RBuilder.MyComponent(radius: Int, color: String) {
  svg {
     ...
  }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢.

Mar*_*tke 6

在撰写本文时,Kotlin似乎没有一个类似于kotlinx.html的svg库.话虽这么说,有可能通过逆向工程kotlin-react和kotlinx.html相互作用的方式在kotlin反应中创建任意xml.或者只使用碱反应功能.

方法1:使用kotlinx.html

import kotlinx.html.HTMLTag 
import react.*
import react.dom.*

// a custom tag builder, reuses the tag(...) function from kotlin-react and HTMLTag from kotlinx.html
inline fun RBuilder.custom(tagName: String, block: RDOMBuilder<HTMLTag>.() -> Unit): ReactElement = tag(block) {
    HTMLTag(tagName, it, mapOf(), null, true, false) // I dont know yet what the last 3 params mean... to lazy to look it up
}

// example use
inline fun RBuilder.mySVG(animTime: Double) {
    svg() {
        attrs["width"] = "800"
        attrs["height"] = "600"
        attrs["viewBox"] = "0 0 800 600"

        custom("circle") {
            attrs["cx"] = 150
            attrs["cy"] = 150
            attrs["r"] = 50.0 + sin(animTime) * 50.0
            attrs["style"] = object {
                val stroke = "black"
                val fill = "red"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

方法2:使用childcreateElement来自react.dom

open class CircleProps (
    val cx: Int,
    val cy: Int,
    val r: Int,
    val stroke: String,
    val fill: String,
    val strokeWidth: Int
    ): RProps {
}

inline fun RBuilder.mySVG2(animTime: Double) {
svg() {
    attrs["width"] = "800"
    attrs["height"] = "600"
    attrs["viewBox"] = "0 0 800 600"

    child(createElement("circle", CircleProps(150,150, 50.0 + sin(animTime) * 50.0, "black", "blue", 3)))
}
Run Code Online (Sandbox Code Playgroud)


Big*_*ich 1

我不确定如何在 Kotlin/React 文件中内联编写 SVG,但是,JetBrain 自己的示例展示了如何在 Kotlin-React 中加载外部 SVG 文件

@JsModule("src/logo/react.svg")
external val reactLogo: dynamic
@JsModule("src/logo/kotlin.svg")
external val kotlinLogo: dynamic

fun RBuilder.logo(height: Int = 100) {
    div("Logo") {
        attrs.jsStyle.height = height
        img(alt = "React logo.logo", src = reactLogo, classes = "Logo-react") {}
        img(alt = "Kotlin logo.logo", src = kotlinLogo, classes = "Logo-kotlin") {}
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您确实弄清楚如何内联执行此操作,请将该解决方案发布回此处供社区使用,谢谢。