Rohit Asked: 2024-10-21 14:07:12 +0800 CST2024-10-21 14:07:12 +0800 CST 2024-10-21 14:07:12 +0800 CST 为什么带有 onClick lambda 的按钮每次点击都会重组两次? 772 为什么每次点击按钮都会重组两次? 代码片段: var counter by remember { mutableIntStateOf(0) } Button(onClick = { counter++ }) { Text(text = "I've been clicked $counter times") } 观察: 当按钮被点击 x 次时,根据布局检查器,按钮会被重组 2 次。 android-jetpack-compose 1 个回答 Voted Best Answer Thracian 2024-10-21T18:13:33+08:002024-10-21T18:13:33+08:00 Surface由于高度变化,在实现过程中会发生重新构图Button。而且通常是点击次数的两倍以上。如果您将手指放在按钮上然后松开,您也可以在松开后观察到重新构图。 Material 库的按钮源代码,我只注释了高度以将其传递给 SideEffect。 @Composable fun MyButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource? = null, elevation: ButtonElevation? = ButtonDefaults.elevation(), shape: Shape = MaterialTheme.shapes.small, border: BorderStroke? = null, colors: ButtonColors = ButtonDefaults.buttonColors(), contentPadding: PaddingValues = ButtonDefaults.ContentPadding, content: @Composable RowScope.() -> Unit ) { @Suppress("NAME_SHADOWING") val interactionSource = interactionSource ?: remember { MutableInteractionSource() } val contentColor by colors.contentColor(enabled) val elevationValue = elevation?.elevation(enabled, interactionSource)?.value ?: 0.dp SideEffect { println("Recomposing... $elevationValue") } Surface( onClick = onClick, modifier = modifier.semantics { role = Role.Button }, enabled = enabled, shape = shape, color = colors.backgroundColor(enabled).value, contentColor = contentColor.copy(alpha = 1f), border = border, elevation = elevationValue, // elevation = elevation?.elevation(enabled, interactionSource)?.value ?: 0.dp, interactionSource = interactionSource ) { CompositionLocalProvider(LocalContentAlpha provides contentColor.alpha) { ProvideTextStyle( value = MaterialTheme.typography.button ) { Row( Modifier .defaultMinSize( minWidth = ButtonDefaults.MinWidth, minHeight = ButtonDefaults.MinHeight ) .padding(contentPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } } } 您可以观察 中的值变化SideEffect。如果您评论 elevation,则不会看到额外的重组。
Surface
由于高度变化,在实现过程中会发生重新构图Button
。而且通常是点击次数的两倍以上。如果您将手指放在按钮上然后松开,您也可以在松开后观察到重新构图。Material 库的按钮源代码,我只注释了高度以将其传递给 SideEffect。
您可以观察 中的值变化
SideEffect
。如果您评论 elevation,则不会看到额外的重组。