[英]Android Compose how to update other Composable function better way?
I just wanna click button can log ComposeableB().or liek this, For example, if you click ComposableA, ComposableB will start an animation instead of updating the data.我只想单击按钮可以记录 ComposeableB()。或者类似这样,例如,如果您单击 ComposableA,ComposableB 将启动 animation 而不是更新数据。
Although with Compose it is generally recommended to pass events to the app logic (like the ViewModel) instead of to the app UI ( Thinking in Compose ), here's how your code could look like if you really need to do that:尽管使用 Compose 通常建议将事件传递给应用程序逻辑(如 ViewModel)而不是应用程序 UI( 在 Compose 中思考),但如果您确实需要这样做,以下是您的代码的外观:
@Composable
fun ComposableA() {
val addLogEntry = remember { mutableStateOf(false) }
Column {
Button(onClick = {
addLogEntry.value = true
}) {
Text(text = "Log")
}
ComposableB(addLogEntry = addLogEntry.value) {
addLogEntry.value = false
}
}
}
@Composable
fun ComposableB(
addLogEntry: Boolean,
onLogEntryAdded: () -> Unit
) {
if (addLogEntry) {
Log.d("Shadowmeld", "onAddLogEntry")
onLogEntryAdded()
}
}
Here you are passing a function as a second parameter (onLogEntryAdded, in lambda expression format) to ComposableB.在这里,您将 function 作为第二个参数(onLogEntryAdded,采用 lambda 表达式格式)传递给 ComposableB。 This passed lambda expression will be called from ComposableB to modify state in ComposableA.
这个通过 lambda 表达式将从 ComposableB 调用以修改 ComposableA 中的 state。
I believe there are better ways of doing this, like ComposableB being declared inside ComposableA (hoisting state to ComposableA) or, if that is not an option, passing the Button onClick event to a ViewModel that both ComposableA and ComposableB can observe.我相信有更好的方法可以做到这一点,比如在 ComposableA 中声明 ComposableB(将 state 提升到 ComposableA),或者,如果这不是一个选项,则将 Button onClick 事件传递给 ComposableA 和 ComposableB 都可以观察到的 ViewModel。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.