如何在 Jetpack Compose 中制作可重用的组件?

How to make reusable components in Jetpack compose?

我正在尝试创建一个 TextField 可重用组件,所以我这样做了

@Composable
fun TextFieldComponent(state: Any, placeholder: String) {
    TextField(
        value = state,
        onValueChange = { textFieldValue -> state = textFieldValue },
        placeholder = { Text(placeholder, color = MaterialTheme.colors.secondary) }
    )
}

但我遇到了这些错误

这就是我调用组件的方式

val textFieldState by rememberSaveable { mutableStateOf("") }
TextFieldComponent(state = textFieldState, placeholder = "Email")

那么有什么解决办法吗?

只要把state变成MutableState<String>,这样你就可以在函数内部修改它了:

@Composable
fun TextFieldComponent(state: MutableState<String>, placeholder: String) {
    TextField(
        value = state.value,
        onValueChange = { textFieldValue -> state.value = textFieldValue },
        placeholder = { Text(placeholder, color = MaterialTheme.colors.secondary) }
    )
}

但是,通常最好为可组合函数提供一个值和一个更改侦听器:

@Composable
fun TextFieldComponent2(value: String, onValueChange: (String) -> Unit, placeholder: String) {
    TextField(
        value = value,
        onValueChange = { textFieldValue -> onValueChange(textFieldValue) },
        placeholder = { Text(placeholder, color = MaterialTheme.colors.secondary) }
    )
}

这样的解决方案更灵活,因为调用者可以很容易地提供值变化的任何行为(感谢@Jakoss)