我在 Jetpack Compose 中有一个嵌套的组件结构,其中深层嵌套的组件需要与 ViewModel 交互。我正在尝试确定处理此交互的最佳方法。
这是我的组件结构:
class MainViewModel : ViewModel() {
fun handleButtonClick() {
// Do something
}
}
// Approach 1: Passing ViewModel down
@Composable
fun ComposableA(viewModel: MainViewModel) {
ComposableB()
ComposableC(viewModel = viewModel)
}
@Composable
fun ComposableC(viewModel: MainViewModel) {
ComposableD(viewModel = viewModel)
}
@Composable
fun ComposableD(viewModel: MainViewModel) {
Button(onClick = { viewModel.handleButtonClick() }) {
Text("Click Me")
}
}
// Approach 2: Using Callbacks
@Composable
fun ComposableA(viewModel: MainViewModel) {
val onButtonClick = { viewModel.handleButtonClick() }
ComposableB()
ComposableC(onButtonClick = onButtonClick)
}
@Composable
fun ComposableC(onButtonClick: () -> Unit) {
ComposableD(onButtonClick = onButtonClick)
}
@Composable
fun ComposableD(onButtonClick: () -> Unit) {
Button(onClick = onButtonClick) {
Text("Click Me")
}
}
Which approach is considered better practice?