我试图理解CompositionLocal
实际上是如何隐含地设置值的,以及需要满足哪些要求才能使其发挥作用,但Android关于Locally scoped data with CompositionLocal的文档无济于事.
有一个示例,通过为color
参数指定新值来更改Text
的 colored颜色 .
// Some composable deep in the hierarchy of MaterialTheme
@Composable
fun SomeTextLabel(labelText: String) {
Text(
text = labelText,
// `primary` is obtained from MaterialTheme's
// LocalColors CompositionLocal
color = MaterialTheme.colors.primary
)
}
但如果您需要这样设置,这并不是隐含的!
然后他们展示了另一个例子,他们通过CompositionLocalProvider
改变了ContentAlpha
,这里Text
suddenly可以隐式地使用新值,即使他们写的是CompositionLocal is what the Material theme uses under the hood.,那么为什么第一个例子不行呢?
@Composable
fun CompositionLocalExample() {
MaterialTheme { // MaterialTheme sets ContentAlpha.high as default
Column {
Text("Uses MaterialTheme's provided alpha")
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text("Medium value provided for LocalContentAlpha")
Text("This Text also uses the medium value")
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.disabled) {
DescendantExample()
}
}
}
}
}
@Composable
fun DescendantExample() {
// CompositionLocalProviders also work across composable functions
Text("This Text uses the disabled alpha now")
}
还有第三个例子,他们展示了如何create your own CompositionLocal
,但在这里,他们explicitly设置了Card
‘S elevation
参数!
@Composable
fun SomeComposable() {
// Access the globally defined LocalElevations variable to get the
// current Elevations in this part of the Composition
Card(elevation = LocalElevations.current.card) {
// Content
}
}
他们创造CompositionLocalProvider
难道不是为了避免这样做吗?
// Bind elevation as the value for LocalElevations
CompositionLocalProvider(LocalElevations provides elevations) {
// ... Content goes here ...
// This part of Composition will see the `elevations` instance
// when accessing LocalElevations.current
}