TextField 'OnValueChange' 在未输入任何输入的情况下调用了两次

问题描述 投票:0回答:1
fun TextFieldWithIconsAndErrorLabel(
    text: String,
    charLimit: Int = Int.MAX_VALUE,
    keyboardType: KeyboardType = KeyboardType.Text,
    onValueChange: (String) -> Unit,
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    var shouldShowMaxCharLimitError by remember { mutableStateOf(false) }

    BasicTextField(
        modifier = Modifier
            .fillMaxWidth(),
        value = text,
        onValueChange = { newInput ->
            if (newInput.length > charLimit) {
                shouldShowMaxCharLimitError = true
            } else {
                shouldShowMaxCharLimitError = false
                onValueChange(newInput)
            }
        },
        keyboardOptions = KeyboardOptions(
            imeAction = ImeAction.Done,
            keyboardType = keyboardType,
        ),
        singleLine = true,
        keyboardActions = KeyboardActions(
            onDone = {
                keyboardController?.hide()
                onValueChange(text)
                shouldShowMaxCharLimitError = false
            }
        ),
    )
    if (shouldShowMaxCharLimitError) {
        Text(
            modifier = Modifier
                .fillMaxWidth(),
            text = "Max character limit exceeded",
            style = TextStyle(
                fontFamily = PoppinsFamily,
                fontWeight = FontWeight.Medium,
                fontSize = 12.sp,
                color = Color.Red,
                textAlign = TextAlign.Start
            ),
        )
    }
}

在上面的代码中,

onValueChange
被多次调用并立即重置布尔值。 对于每个文本输入,此 lambda 都会被调用两次。

onValueChange = { newInput ->
            if (newInput.length > charLimit) {
                shouldShowMaxCharLimitError = true
            } else {
                shouldShowMaxCharLimitError = false
                onValueChange(newInput)
            }
        }
android android-studio android-jetpack-compose android-jetpack
1个回答
0
投票

将 onValueChange 更改为此

onValueChange = { newInput ->
        shouldShowMaxCharLimitError = newInput.length > charLimit
        if (!shouldShowMaxCharLimitError) {
            onValueChange(newInput)
        }
    }

并删除 onDone 回调中对 onValueChange(text) 的调用

onDone = {
    keyboardController?.hide()
    // Remove the following line
    // onValueChange(text)
    shouldShowMaxCharLimitError = false
}
© www.soinside.com 2019 - 2024. All rights reserved.