在@Composable函数内调用@Composable仍报上下文错误如何解决?
报错原因
你调用RadioGroupItem时传入的承载Row的尾随lambda参数,本身没有被标记为@Composable,不具备Composable函数调用上下文,因此你在该lambda内调用Row、Image、ClickableText等Composable组件时触发了编译规则校验报错。
可行解决方法
1. 修正RadioGroupItem的组件声明
如果你是自定义的RadioGroupItem组件,需要给内容参数加上@Composable注解,示例:
错误的声明示例:
// 错误:content参数未加@Composable注解 fun RadioGroupItem( selected: Boolean, onSelect: () -> Unit, content: () -> Unit ) { // 组件实现 }
修正后的声明:
// 正确:给content参数加上@Composable注解 fun RadioGroupItem( selected: Boolean, onSelect: () -> Unit, content: @Composable () -> Unit ) { // 组件实现 }
如果你使用的是第三方库/View系统的RadioGroup、RadioGroupItem:
- 若为Android View系统的组件,需要替换为Jetpack Compose生态的单选组件实现,不可混用View和Compose的内容插槽
- 若为第三方Compose库组件,可查阅组件文档确认内容插槽的调用规则,或者自行封装符合需求的单选组件
2. 修正现有代码的逻辑错误
你现有代码中还存在两处逻辑问题:
RadioGroupItem的selected参数被写死为false,永远不会触发选中状态,需要改为selected = selectedOption == index- 若你没有特殊的图片显示逻辑,
imageStateCheck参数可以直接替换为index == selectedOption判断,减少不必要的回调传递
修正后的完整代码示例
@Composable fun CustomRadioGroupItemComponent( radioOptions: List<String>, onSelectBehavior: (optionIndex: Int, onOptionSelected: (Int) -> Unit) -> Unit, imageStateCheck: (selectedOption: Int) -> Boolean ): Int { if (radioOptions.isNotEmpty()) { val (selectedOption, onOptionSelected) = remember { mutableStateOf(0) } RadioGroup { radioOptions.forEachIndexed { index, item -> RadioGroupItem( // 修正选中状态判断 selected = selectedOption == index, onSelect = { onSelectBehavior(index, onOptionSelected) } ) { Row(modifier = Modifier.padding(10.dp)) { if (imageStateCheck(selectedOption)) { Image( painter = painterResource(id = R.drawable.ic_radio_button_checked), contentDescription = null ) } else { Image( painter = painterResource(id = R.drawable.ic_radio_button_unchecked), contentDescription = null ) } ClickableText( text = AnnotatedString(item), style = TextStyle(fontFamily = FontFamily(Font(R.font.nunito_light))), onClick = { onSelectBehavior(index, onOptionSelected) } ) } } } } return selectedOption } else { return 0 } }
内容的提问来源于stack exchange,提问作者LAO
相关产品推荐
相关产品推荐

