Jetpack Compose调用Composable函数报错:上下文不符问题
解决Composable函数在点击回调中调用的错误问题
出现@Composable invocations can only happen from the context of a @Composable function错误的核心原因是:Composable函数只能在Composable作用域内调用,而clickable的onClick回调是普通的非Composable Lambda,不属于Composable上下文,所以不能在这里直接调用RotatingImage()。
正确的做法是用状态变量控制Composable的显示逻辑,而不是在点击回调中直接调用Composable函数。修改后的代码如下:
@Composable fun RotatingImage() { val rotationState = rememberInfiniteTransition() val rotation by rotationState.animateFloat( initialValue = 0f, targetValue = 360f, animationSpec = infiniteRepeatable( animation = keyframes { durationMillis = 3000 }, repeatMode = RepeatMode.Restart ), label = "" ) val image: Painter = painterResource(id = R.drawable.andew) // 替换为你的资源 Image( painter = image, contentDescription = null, // 不需要描述可设为null modifier = Modifier .size(100.dp) // 设置图片尺寸 .rotate(rotation) // 应用旋转动画 ) } @Composable fun Clickc() { var count by remember { mutableStateOf(0) } // 新增状态变量,控制旋转图片的显示 var showRotatingImage by remember { mutableStateOf(false) } Column { Text(text = count.toString(), color = Color.White) Image( painter = painterResource(id = R.drawable.watermelon), contentDescription = "im2", modifier = Modifier.clickable(onClick = { count++ // 计数到10时更新状态 if (count == 10) { showRotatingImage = true } }) ) // 在Composable作用域内,根据状态决定是否渲染RotatingImage if (showRotatingImage) { RotatingImage() } } }
修改说明:
- 新增
showRotatingImage可变状态变量,用来标记是否需要显示旋转图片 - 点击回调中仅更新状态值,不直接调用Composable函数
- 在
Column这个Composable作用域内,根据showRotatingImage的布尔值决定是否渲染RotatingImage
内容的提问来源于stack exchange,提问作者Umaq
相关产品推荐
相关产品推荐

