无法重新分配 Jetpack Compose val

Jetpack Compose val cannot be reassigned

提问人:Jorpy 提问时间:6/26/2023 更新时间:6/26/2023 访问量:114

问:

我想传递状态,但它抛出错误“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")
    }
}
Android 用户界面 android-jetpack

评论


答:

2赞 Francesc 6/26/2023 #1

你应该让你的可组合项成为无状态的,并向上传递事件,像这样改变它,其中顶部的可组合项负责改变标志

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