Jetpack Compose val 无法重新赋值

huangapple go评论64阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月26日 00:25:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定