我們有下面的組合,效果很好。
@Composable
fun MyInnerControl() {
var timerStartStop by remember { mutableStateOf(true) }
Button(onClick = {
timerStartStop = !timerStartStop
}) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
但是如果我們有timerStartStop通過函式引數,我不能做如下
@Composable
fun MyInnerControl(timerStartStop: Boolean) {
Button(onClick = {
timerStartStop = !timerStartStop
}) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
我可以通過如下方式,但隨后我必須將我的更改timerStartStop為timerStartStop.value
@Composable
fun MyInnerControl(timerStartStop: MutableState<Boolean>) {
Button(onClick = {
timerStartStop.value = !timerStartStop.value
}) {
Text(if (timerStartStop.value) "Stop" else "Start")
}
}
有什么方法可以MutableState<Boolean>傳遞引數,但在函式中我們可以使用委托方法,即使用timerStartStop而不是timerStartStop.value?
uj5u.com熱心網友回復:
Jetpack Compose 告訴您尊重單一事實來源原則,這意味著如果您想在函式內部更改該狀態,則不能將狀態作為引數傳遞。
因此,通常您必須選擇以下兩種方法之一:
- 同時傳遞 timerStartStop 變數和 onClick 回呼
@Composable
fun MyInnerControl(timerStartStop: Boolean, onClick: ()->Unit) {
Button(onClick = onClick) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
- 這些都不通過
@Composable
fun MyInnerControl() {
var timerStartStop by remember { mutableStateOf(true) }
Button(onClick = {
timerStartStop = !timerStartStop
}) {
Text(if (timerStartStop) "Stop" else "Start")
}
}
uj5u.com熱心網友回復:
我認為最好應用適當的狀態提升方法,并MyInnerControl通過以下方式提供讀取和編輯引數的能力。
@Composable
fun ParentComposable() {
val isTimerRunning by remember { mutableStateOf(false) } }
MyInnerControl(
isTimerRunning = isTimerRunning,
flipTimerState {
isTimerRunning = !isTimerRunning
}
}
}
@Composable
fun MyInnerControl(
isTimerRunning: Boolean,
flipTimerState: () -> Unit,
) {
Button(
onClick = { flipTimerState() }
) {
Text(if (isTimerRunning) "Stop" else "Start")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411496.html
標籤:
