文档管理中心

TextInput组件禁止长按事件

问题现象

TextInput组件长按输入框内文本时会自动选中文本,如何实现禁止长按事件?

效果预览

背景知识

  • TextInput是单行文本输入框组件,仅支持单文本样式。当用户长按输入框内的文本时会自动选中文本,其默认触发时间为500ms。
  • LongPressGesture用于触发长按手势事件,触发长按手势的最少手指数为1,默认最短长按时间为500毫秒。可配置duration参数控制最短长按时长。

解决方案

系统长按事件触发时间为500ms,可以设置LongPressGesture长按手势事件触发时间小于500ms,实现拦截系统长按事件的效果。

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct TextInputNoLongPress {
  4. @State message: string = '';
  5. build() {
  6. Column() {
  7. Text(`输入的内容: ${this.message}`)
  8. .margin({ top: 100, bottom: 30 });
  9. TextInput({ placeholder: '请输入内容' })
  10. .borderRadius(0)
  11. .onChange((value: string) => {
  12. this.message = value;
  13. })
  14. .gesture(
  15. LongPressGesture({ repeat: true, duration: 400 })
  16. // 由于repeat设置为true,长按动作存在时会连续触发,触发间隔为duration(默认值500ms
  17. .onAction(() => {
  18. return true;
  19. })
  20. .onActionEnd(() => {
  21. })
  22. )
  23. .selectionMenuHidden(true);
  24. }
  25. .height('100%')
  26. .width('100%')
  27. .padding(16);
  28. }
  29. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词