问题描述
Modifier.composed { ... }
什么时候有用?如果我可以简单地对 Modifier.composed { PaddingModifier(...) }
执行 Modifier.padding()
,为什么我需要它?
When is Modifier.composed { ... }
useful? Why would I need it if I could simply do Modifier.padding()
over Modifier.composed { PaddingModifier(...) }
?
推荐答案
Modifier.composed 允许创建一个对具体化 实例特定、有状态 修饰符.来自文档:
Modifier.composed allows the creation of a composition-aware modifier-factory that's useful for materializing instance-specific, stateful modifiers. From the docs:
声明一个修改器的即时组合,它将为它修改的每个元素组合.组合可用于实现有状态修饰符,这些修饰符对每个修改过的元素都有特定于实例的状态,允许同一个修饰符实例安全地重用于多个元素,同时保持元素特定的状态.
换句话说,它允许您将提升状态注入特定于元素的 Modifier
并使用 remember
、DisposableEffect
、环境
等,例如:
In other words, it allows you to inject hoisted state into an element-specific Modifier
and use remember
, DisposableEffect
, Ambient
, etc. For instance:
fun Modifier.fancyModifier(
enabled: Boolean = false,
onClick: () -> Unit = {}
) = composed(inspectorInfo = debugInspectorInfo {
name = "fancyModifier"
value = enabled
}) {
var paddingValue by remember { mutableStateOf(0.dp) }
onCommit(enabled) {
paddingValue = if (enabled) 16.dp else 0.dp
}
fillMaxWidth()
.clickable { onClick() }
.padding(paddingValue)
}
LazyColumnFor(items = List(size = 10) { "$it" }) {
var enabled by remember { mutableStateOf(false) }
Text(
text = "fancy modifier",
modifier = Modifier.fancyModifier(enabled) {
enabled = !enabled
}
)
}
您还可以声明 InspectorInfo
以帮助使用 debugInspectorInfo
进行调试.来自文档:
You can also declare InspectorInfo
to help with debugging by using debugInspectorInfo
. From the docs:
如果指定了inspectorInfo,则该修饰符将在开发期间对工具可见.指定原始修饰符的名称和参数.以及可选地声明 InspectorInfo
以帮助调试.
如果您想要跟踪的值不止一个,您可以使用 properties
字段而不是 value
.
You can use the properties
field instead of value
if you have more than value you'd like to track.
注意:debugInspectorInfo lambda 从 release
构建中删除.
Note: debugInspectorInfo lambdas are removed from release
builds.
class FancyModifierTest {
@Before
fun setup() {
isDebugInspectorInfoEnabled = true
}
@After
fun teardown() {
isDebugInspectorInfoEnabled = false
}
@Test
fun testFancyModifierInspectableValue() {
val modifier = Modifier.fancyModifier() as InspectableValue
assertEquals(modifier.nameFallback, "fancyModifier")
assertEquals(modifier.valueOverride, false)
assertEquals(modifier.inspectableElements.toList().size, 0)
}
}
这里有一些更实际的例子:
Here are some more practical examples:
这篇关于你什么时候需要 Modifier.composed { ... }?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!