【问题标题】:Composable getting bloated with too many callbacks passed可组合项因传递的回调过多而变得臃肿
【发布时间】:2022-11-23 15:38:55
【问题描述】:

这是我当前的可组合项:

@Composable
fun MyComposable(
    onPress1: () -> Unit,
    onPress2: () -> Unit,
    onPress3: () -> Unit,
    onPress4: () -> Unit,
    onPress5: () -> Unit,
) {
    Button(onClick = onPress1) { Text(text = "Press 1")}
    Button(onClick = onPress2) { Text(text = "Press 2")}
    Button(onClick = onPress3) { Text(text = "Press 3")}
    Button(onClick = onPress4) { Text(text = "Press 4")}
    Button(onClick = onPress5) { Text(text = "Press 5")}
}

有没有办法减少这种情况,类似于 react 如何使用 useReducer 挂钩操作类型和操作有效负载

【问题讨论】:

    标签: android kotlin android-jetpack-compose


    【解决方案1】:

    您可以使用密封类来创建可以根据需要在项目的不同位置重复使用的点击事件。

    // Create your different click events
    sealed class MyClickEvent {
        object Press1: MyClickEvent()
        object Press2: MyClickEvent()
        object Press3: MyClickEvent()
        object Press4: MyClickEvent()
        // You can create a click event that passes arguments
        data class Press5(val arg: String): MyClickEvent()
    }
    
    // Handle each click event ( This function should be inside your view model )
    fun onMyClickEvent(event: MyClickEvent) {
        when(event) {
            is MyClickEvent.Press1 -> println("Press1")
            is MyClickEvent.Press2 -> println("Press2")
            is MyClickEvent.Press3 -> println("Press3")
            is MyClickEvent.Press4 -> println("Press4")
            is MyClickEvent.Press5 -> println("Press5: ${event.arg}")
        }
    }
    
    @Composable
    fun MyMainComposable() {
        MyComposable(
            onMyClickEvent = { event -> onMyClickEvent(event) }
        )
    }
    
    // Pass only single lambda for different click events
    @Composable
    fun MyComposable(
        onMyClickEvent: (event: MyClickEvent) -> Unit,
    ) {
        Button(onClick = { onMyClickEvent(MyClickEvent.Press1) }) {
            Text(text = "Press 1")
        }
        Button(onClick = { onMyClickEvent(MyClickEvent.Press2) }) {
            Text(text = "Press 2")
        }
        Button(onClick = { onMyClickEvent(MyClickEvent.Press3) }) {
            Text(text = "Press 3")
        }
        Button(onClick = { onMyClickEvent(MyClickEvent.Press4) }) {
            Text(text = "Press 4")
        }
        Button(onClick = { onMyClickEvent(MyClickEvent.Press5(arg = "data")) }) {
            Text(text = "Press 5")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      相关资源
      最近更新 更多