HarmonyOS 鸿蒙Next中list中有多个TextInput,输入text时光标乱窜?
HarmonyOS 鸿蒙Next中list中有多个TextInput,输入text时光标乱窜?
如下code,list中有多个TextInput,在某个TextInput中输入字符时,光标会乱跑到别的TextInput中,bug?
复现步骤是:点击屏幕下方的TextInput,输入一个数字或者一个英文字符,光标会自动跳到上方第二个或第三个TextInput中
模拟器和真机均可复现。
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State list: string[] = ['aa', '22', '33', '44', '55', '66', '77']
build() {
RelativeContainer() {
List() {
ForEach(this.list, (item: string, index) => {
ListItem() {
TextInput({
text: this.list[index]!!,
placeholder: 'text...'
})
}
})
}
}
.height('100%')
.width('100%')
}
}
HarmonyOS 5.1.0 Release SDK, inclusion of OpenHarmony SDK Ohos_sdk_public 5.1.0.125 (API Version 18 Release) as is。
模拟器API 18
更多关于HarmonyOS 鸿蒙Next中list中有多个TextInput,输入text时光标乱窜?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
interface TextItem { id: string; value: string; }
@Entry @Component struct Index { @State list: TextItem[] = [ { id: ‘1’, value: ‘aa’ }, { id: ‘2’, value: ‘22’ }, { id: ‘3’, value: ‘33’ }, { id: ‘4’, value: ‘44’ }, { id: ‘5’, value: ‘55’ }, { id: ‘6’, value: ‘66’ }, { id: ‘7’, value: ‘77’ }, { id: ‘8’, value: ‘88’ }, { id: ‘9’, value: ‘99’ }, { id: ‘10’, value: ‘10’ }, // 增加更多项便于测试滚动 { id: ‘11’, value: ‘11’ }, { id: ‘12’, value: ‘12’ }, ]
build() { Column() { List({ space: 5 }) { ForEach( this.list, (item: TextItem) => { ListItem() { // 关键:用自定义组件隔离每个TextInput的状态 InputItem({ item: item }) } }, (item: TextItem) => item.id // 用唯一id作为key(即使增删项也不会乱) ) } .width(‘100%’) .height(‘100%’) .padding(10) // 关闭列表项复用优化(极端情况,性能可能下降但状态稳定) .cachedCount(0) } .height(‘100%’) .width(‘100%’) } }
// 自定义组件:完全隔离每个TextInput的状态 @Component struct InputItem { @Prop item: TextItem
build() { TextInput({ text: this.item.value, placeholder: ‘text…’ }) .width(‘100%’) .height(50) .border({ width: 1 }) .padding(10) // 输入时立即同步数据 .onChange((value) => { this.item.value = value }) } }
更多关于HarmonyOS 鸿蒙Next中list中有多个TextInput,输入text时光标乱窜?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
我试一下 我是API20 鸿蒙6.0 真机 mate70pro 跟楼主说得BUG 一样
我预计是所有得TextInput 都是同一个控制器所以导致问题出现
真机API17测试没有问题
我用的真机能复现。HarmonyOS 5.1.0,软件版本5.1.0.128,API版本5.0.5(17)
复现步骤是:点击屏幕下方的TextInput,输入一个数字或者一个英文字符,光标会自动跳到上方第二个或第三个TextInput中,
这是一个已知的HarmonyOS Next中TextInput在List中的焦点管理问题。问题主要出在ForEach渲染机制和TextInput焦点保持上。
解决方案是给每个TextInput添加唯一的id属性,并确保key值正确绑定。修改后的代码如下:
ForEach(this.list, (item: string, index) => {
ListItem() {
TextInput({
text: this.list[index]!!,
placeholder: 'text...'
})
.id(`input_${index}`) // 添加唯一id
}
}, (item, index) => index.toString()) // 确保key生成器
这个问题的根本原因是List复用机制导致组件状态混乱。当TextInput没有唯一标识时,系统无法正确跟踪焦点状态。添加id属性和正确的key生成器后,系统就能正确管理各个TextInput的焦点状态了。
如果问题仍然存在,可以尝试在TextInput外层包裹一个Column或Row容器,这有时也能帮助稳定焦点行为。