如何将JetpackCompose中的子项传递给自定义可组合项?

我很好奇是否可以将可组合物传递给自定义可组合物块。然后在其定义中呈现。我在想可以采用 vararg + 函数文字方法,但找不到任何信息。

//definition
@Composable
fun Content() {
    Row(modifier = Modifier.fillMaxWidth()) {
        //insert a(), b(), ..., z() so that they render in the row
    }
}

//usage
Content() {
    a()
    b()
    ...
    z()
}

这样的东西已经存在了吗?您可以通过这种方式使用 Jetpack Compose。行实现必须以某种方式处理文本。

Row(){
    Text("a")
    Text("b")
    Text("c")
}

回答

在查看了 Row、RowScope 的实现并找到了这篇文档之后。这可以通过以下代码示例来实现。类型为的内容函数参数@Composable() () -> Unit被传递到行中。

//definition
@Composable
fun MyCustomContent(
    modifier: Modifier = Modifier,
    content: @Composable() () -> Unit
) {
    Row(modifier = modifier) {
        content()
    }
}

//usage
MyCustomContent() {
    a()
    b()
    z()
}

  • "name it as you please" -- you may start getting Lint warnings. The official convention is that this parameter is named `content`.

以上是如何将JetpackCompose中的子项传递给自定义可组合项?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>