6

我正在尝试在我的create-react-kotlin-app中使用这个库:

https://material-ui-next.com/

我想生成一堆类型安全的包装器。我是这样开始的:

@file:JsModule("material-ui")

package material

import react.RState
import react.React
import react.ReactElement

external class Typography : React.Component<dynamic, RState> {
    override fun render(): ReactElement
}

...

fun RBuilder.typography(
    classes: String = "",
    variant: Variant = Variant.body1,
    align: Align = Align.inherit,
    color: Color = Color.default,
    gutterBottom: Boolean = false,
    noWrap: Boolean = false,
    paragraph: Boolean = false,
    handler: RHandler<dynamic>
) = child(Typography::class) {
    attrs {
        this.className = classes
        this.align = align.name
        this.color = color.name
        this.variant = variant.name
        this.gutterBottom = gutterBottom
        this.noWrap = noWrap
        this.paragraph = paragraph
    }
    handler()
}

并像这样使用它:

typography(variant = Variant.title, color = Color.inherit) {
    +"Hello World"
}

这是正确的方法吗?

4

2 回答 2

0

我也有兴趣在 Kotlin 代码中添加一个 ReactJS 3rd 方组件。请查看以下帖子,我将不胜感激有关那里提出的解决方案的任何反馈:

如何在 React-Kotlin 中导入节点模块?

于 2018-07-29T00:07:53.140 回答
0

确实这是正确的方法,但可以使其成为最佳方法,如下所示

MaterialUi.kt

@file:JsModule("material-ui")

package material

import react.RState
import react.RProps
import react.React
import react.ReactElement

external interface TypographyProps : RProps {
    var className: String
    var align : String
    var color : String
    var variant : String
    var gutterBottom : String
    var noWrap : String
    var paragraph : String
}

@JsName("Typography")
external class Typography : RComponent<TypographyProps, RState> {
    override fun render(): ReactElement
}

然后创建另一个文件,比如说

MaterialUiDsl.kt

fun RBuilder.typography(
    classes: String = "",
    variant: Variant = Variant.body1,
    align: Align = Align.inherit,
    color: Color = Color.default,
    gutterBottom: Boolean = false,
    noWrap: Boolean = false,
    paragraph: Boolean = false,
    handler: RHandler<TypographyProps> // notice the change here
) = child(Typography::class) {
    attrs {
        this.className = classes
        this.align = align.name
        this.color = color.name
        this.variant = variant.name
        this.gutterBottom = gutterBottom
        this.noWrap = noWrap
        this.paragraph = paragraph
    }
    handler()
}

如果上面的文件对你来说已经很冗长了(就像我经常感觉的那样),你可以把它改成

MaterialUiDsl.kt

fun RBuilder.typography(handler: RHandler<dynamic>) = child(Typography::class,handler)

您可以随时使用它

typography {
    attr {
        className = "my-typo"
        color = "#ff00ff"
        //. . .
    }
}

十分简单

于 2018-11-20T20:34:22.667 回答