gpt4 book ai didi

android - 可组合项因传递的回调过多而变得臃肿

转载 作者:行者123 更新时间:2023-12-03 08:00:18 25 4
gpt4 key购买 nike

这是我当前的可组合项:

@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钩子(Hook)操作类型和操作负载

最佳答案

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

// 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")
}
}

关于android - 可组合项因传递的回调过多而变得臃肿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74543084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com