# KeyboardInputComponent 键盘输入组件

# 概述

KeyboardInputComponent 实现唤起/收起键盘、监听输入事件的能力。

# 注意

一般推荐使用 UITextInput 组件实现文本输入框功能。但如需实现自定义键盘能力,可参阅本文档。

# 唤起/收起键盘

首先要将 KeyboardInputComponent 挂载到 entity 上:

const comp = entity.addComponent(engine.KeyboardInputComponent);

通过 showKeyboard 方法唤起键盘:

comp.showKeyboard({ // 参数与小程序 wx.showKeyboard() 接口一致
  defaultValue: "Hello",
  maxLength: 10,
  multiple: false,
  confirmHold: true,
  confirmType: "done",
});

通过 hideKeyboard 方法收起键盘:

comp.hideKeyboard({
  // 参数与小程序 wx.hideKeyboard() 保持一致
});

# 更新键盘内容

comp.updateKeyboard({
  value: "new text" // 参数与小程序 wx.updateKeyboard() 保持一致
});

# 键盘事件

若要监听键盘事件,推荐在 scriptComponent 自定义组件中进行相关处理。 首先要将自定义组件与 KeyboardInputComponent 挂载到同一个 entity 上。

class MyScript extends engine.Script {
  // 自定义组件
}

// 将二者挂载到同一个 entity 上
const comp = entity.addComponent(engine.KeyboardInputComponent);
const myComp = entity.addComponent(MyScript);

在自定义组件中实现相关 on 方法,以实现监听键盘事件:

class MyScript extends engine.Script {
  onKeyboardInput(text) {
    console.log('用户输入了文本:', text);
  }

  onKeyboardComplete(text) {
    console.log('用户完成输入:', text);
  }

  onKeyboardConfirm(text) {
    console.log('用户点击确认按钮,文本是:', text);
  }
}

原理是,KeyboardInputComponent 会自动寻找 entity 内实现了上述 on 方法的组件,并调用这些方法。 因此,如需实现自定义的键盘能力,可编写自定义组件,在组件内实现对 KeyboardInputComponent 的方法调用(如唤起键盘)和键盘事件监听。