我正在尝试喷气背包撰写,并有一个基本的可组合文本字段,它接受布尔变量进行验证。但是,它无法正确更新,仅在初始化时工作。
class RegistrationActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
var name = "zzz"
BasicField(
title = "Last Name",
value = name,
onValueChange = {name = it},
placeholder = "Enter Last Name",
validation = (name.length>2&&name.contains("zzz"))
)
}
}}
可组合:
@Composable
fun BasicField(title: String,
value: String,
onValueChange: (String) -> Unit,
placeholder: String,
maxLines: Int = 1,
validation: Boolean ) {
var fieldValue by remember { mutableStateOf(TextFieldValue(value)) }
BasicTextField(
maxLines = maxLines,
value = fieldValue,
onValueChange = {
fieldValue = it
if(fieldValue.text.length>5){//this part works
Log.e("error","valid string")
}else{
Log.e("error","invalid string")
}
if(validation){//this part doesnt work
Log.e("error","custom validation works")
}else{
Log.e("error","custom validation failed")
}
},
) }
我在可组合物内部有一个基本的验证,它检查有效的字符串长度,但是当逻辑来自外部时,它不起作用。我感谢任何帮助或提示谢谢!
你需要在撰写中将你的名字作为状态。在这里,我们使用了两件事。
>
名称
定义为状态。它在作文中被记住。因此,每当这个可组合函数进入重新组合时,这个名称都不会被重新分配。
使用启动效果
来执行日志语句。因此,LaunchedEffect将从键开始,当键更改时,此效果将重新启动。
class RegistrationActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// 1
val name = remember { mutableStateOf("") }
BasicField(
title = "Last Name",
value = name.value,
onValueChange = {name.value = it},
placeholder = "Enter Last Name",
validation = (name.value.length>2&&name.value.contains("zzz"))
)
}
}}
@Composable
fun BasicField(title: String,
value: String,
onValueChange: (String) -> Unit,
placeholder: String,
maxLines: Int = 1,
validation: Boolean ) {
// 2
LaunchedEffect(key = value) {
if(value.length>5){
Log.e("error","valid string")
}else{
Log.e("error","invalid string")
}
if(validation){
Log.e("error","custom validation works")
}else{
Log.e("error","custom validation failed")
}
}
BasicTextField(
maxLines = maxLines,
value = value,
onValueChange = {
onValueChange(it)
},
)
}