英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论