如何实现图片所示的已输入内容不可删除的TextField组件?

实现TextField固定内容不可删除的方案
这个效果本质是给输入框设置不可编辑的固定前缀,阻止用户删除这部分预设内容,不同技术栈的极简实现如下:
Web端(HTML + 原生JS)
监听输入框的操作事件,拦截所有修改固定前缀的行为:
// 替换为你需要固定的不可删除内容 const fixedContent = "https://"; const inputEl = document.getElementById("target-input"); // 初始化填充固定内容 inputEl.value = fixedContent; // 监听键盘操作,阻止删除固定内容 inputEl.addEventListener("keydown", (e) => { const cursorPos = inputEl.selectionStart; // 光标在固定内容范围内时,禁止删除、左移等修改前缀的操作 if (cursorPos < fixedContent.length) { if (["Backspace", "Delete", "ArrowLeft"].includes(e.key) || e.ctrlKey) { e.preventDefault(); } // 强制将光标定位到固定内容末尾 inputEl.selectionStart = inputEl.selectionEnd = fixedContent.length; } }); // 兜底监听input事件,防止粘贴、拖拽等操作修改前缀 inputEl.addEventListener("input", () => { if (!inputEl.value.startsWith(fixedContent)) { inputEl.value = fixedContent + inputEl.value.replace(fixedContent, ""); inputEl.selectionStart = inputEl.selectionEnd = fixedContent.length; } });
iOS 端(SwiftUI)
对输入绑定值做实时校验,强制保留固定前缀:
struct CustomTextFieldView: View { // 不可删除的固定前缀 private let fixedPrefix = "https://" @State private var inputContent = "https://" var body: some View { TextField("请输入内容", text: $inputContent) .onChange(of: inputContent) { newValue in // 输入内容不匹配前缀时自动恢复 if !newValue.starts(with: fixedPrefix) { inputContent = fixedPrefix + newValue.replacingOccurrences(of: fixedPrefix, with: "") } } } }
Android 端(Jetpack Compose)
在输入回调中过滤输入内容,永久保留前缀:
@Composable fun UnDeleteableTextField() { val fixedPrefix = "https://" var inputContent by remember { mutableStateOf(fixedPrefix) } TextField( value = inputContent, onValueChange = { newValue -> inputContent = if (newValue.startsWith(fixedPrefix)) { newValue } else { fixedPrefix + newValue.removePrefix(fixedPrefix) } }, label = { Text("请输入内容") } ) }
内容的提问来源于stack exchange,提问作者MamaTo Vai
相关产品推荐
相关产品推荐

