英文:
Jetpack Compose val cannot be reassigned
问题
我想传递状态,但它抛出错误 "val 无法重新赋值"。
英文:
I want to pass state but it throws error "val cannot be reassigned".
@Composable
fun MyUi() {
var showContent by remember { mutableStateOf(false) }
if (showContent) {
MyButton(showContent)
}
}
@Composable
fun MyButton(showContent: Boolean) {
// very long content
Button(onClick = {
showContent = true
}) {
Text(text = "Very long content")
}
}
答案1
得分: 2
你应该将你的可组合项(composables)设计成无状态的,并将事件传递给上层,修改如下,其中顶层可组合项负责修改标志:
@Composable
fun MyUi() {
var showContent by remember { mutableStateOf(false) }
if (!showContent) {
MyButton(
onClick = {
showContent = true
}
)
}
}
@Composable
fun MyButton(onClick: () -> Unit) {
// 非常长的内容
Button(onClick = onClick) {
Text(text = "非常长的内容")
}
}
英文:
You should make your composables statelesss and pass events up, change it like this, where the top composable is responsible for mutating the flag
@Composable
fun MyUi() {
var showContent by remember { mutableStateOf(false) }
if (showContent) {
MyButton(
onClick = {
showContent = true
}
)
}
}
@Composable
fun MyButton(onClick: () -> Unit) {
// very long content
Button(onClick = onClick) {
Text(text = "Very long content")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论