Jetpack Compose – 应该将修饰符参数仅应用于最外层/最顶层视图吗?

huangapple go评论74阅读模式
英文:

Jetpack Compose - Should modifier parameter be applied to the outer / top most view only?

问题

在Jetpack Compose中,当将一个修饰符传递给我的可组合组件时,该修饰符应该只应用于最外层视图,还是应用于所有子视图?

以下是一个快速示例:

fun SomeComposable(modifier: Modifier = Modifier) {
    Column(modifier = modifier) {
        Text(modifier = modifier.extraModifiersIfNeeded(), text = "Text")
        Text(modifier = modifier.extraModifiersIfNeeded(), text = "Text")
        Text(modifier = modifier.extraModifiersIfNeeded(), text = "Text")
    }
}

我最初会假设这是不正确的,因为传递给SomeComposable的任何修饰符也会更改所有子视图。

是否有任何明确定义这一点的文档?我可以请您提供文档链接吗?

谢谢!

英文:

In jetpack compose, when passing a modifier into my composable, should the modifier be applied only to the outer most view, or all of the subviews as well?

Here's a quick example:

fun SomeComposable(modifier: Modifier = Modifier) {
    Column(modifier = modifier) {
        Text(modifier = modifier.extraModifiersIfNeeded(), text = "Text")
        Text(modifier = modifier.extraModifiersIfNeeded(), text = "Text")
        Text(modifier = modifier.extraModifiersIfNeeded(), text = "Text")
    }
}

I would initially assume this is incorrect, because any modifier passed into SomeComposable would also change all of the subviews.

Are there any documentations making this very clear? Can I please have a link to any documentations?

Thank you!

答案1

得分: 4

当您将修饰符传递给可组合项时,它应该升级到对您的用例有意义的最高级别。这是因为您可能会在应用填充到您的示例时产生意外的副作用。Column将填充应用于其内容,但然后每个Text可组合项将有额外的填充。

文档建议“将它们提取到可能的最高级别”。

英文:

When you pass a modifier to a composable, it should be elevated to the highest level that makes sense for your use case. This is because you could have unintended side effects say when you apply padding to your example. The Column will have the padding applied to its contents, but then there would be additional padding to each Text composable.

This documentation says to "extract them to the highest level possible".

答案2

得分: 0

首先,modifier 仅显式应用于那些需要这些修改的 composable 函数。

我们将 modifier 传递给最外层的 composable,以使我们的 composable 函数更加健壮和可重用。

英文:

First , modifier is applied (explicitly) only to those composable functions which needs those modifications.

We pass the modifier to outermost composable to make our composable function more robust and reusable.

huangapple
  • 本文由 发表于 2023年3月7日 00:32:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定