# KeyboardInputComponent keyboard input component
# Overview
KeyboardInputComponent implements the ability to awaken/retract the keyboard and listen for input events.
# Notice
It is generally recommended to use the UITextInput component to realize the text input box function. But if you need to implement custom keyboard capabilities, you can refer to this document.
# Arouse / put away the keyboard
First, mount the KeyboardInputComponent on the entity:
const comp = entity.addComponent(engine.KeyboardInputComponent);
Use the showKeyboard
method to call up the keyboard:
comp.showKeyboard({ // The parameters are consistent with the applet wx.showKeyboard() interface
defaultValue: "Hello",
maxLength: 10,
multiple: false,
confirmHold: true,
confirmType: "done",
});
Use the hideKeyboard
method to hide the keyboard:
comp.hideKeyboard({
// The parameters are consistent with the applet wx.hideKeyboard()
});
# Update keyboard content
comp.updateKeyboard({
value: "new text" // The parameters are consistent with the applet wx.updateKeyboard()
});
# Keyboard events
If you want to monitor keyboard events, it is recommended to perform related processing in the scriptComponent custom component. First, mount the custom component and KeyboardInputComponent to the same entity.
class MyScript extends engine.Script {
// Custom component
}
// Mount the two to the same entity
const comp = entity.addComponent(engine.KeyboardInputComponent);
const myComp = entity.addComponent(MyScript);
Implement related on
methods in custom components to monitor keyboard events:
class MyScript extends engine.Script {
onKeyboardInput(text) {
console.log('User entered text:', text);
}
onKeyboardComplete(text) {
console.log('User completed input:', text);
}
onKeyboardConfirm(text) {
console.log('The user clicks the confirmation button, the text is:', text);
}
}
The principle is that KeyboardInputComponent will automatically find components in the entity that implement the above on
method, and call these methods.
Therefore, if you need to implement a custom keyboard capability, you can write a custom component to implement method calls to KeyboardInputComponent (such as awakening the keyboard) and keyboard event monitoring in the component.