验证码输入框组件?

APP常用场景需要用到验证码功能,是常用的组件。希望能封装成一个组件以便复用。

阅读 598
1 个回答

解决方案

demo如下:

import { inputMethod } from '@kit.IMEKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Extend(Text)
function verifyCodeUnitStyle() {
  .fontWeight(60)
  .textAlign(TextAlign.Center)
  .width(60)
  .height('100%')
  .margin({ left: 5, right: 5 })
  .border({
    width: { bottom: 1 },
    color: { bottom: Color.Grey },
    style: { bottom: BorderStyle.Solid }
  })
}

@Entry
@Component
struct PayingDemo {
  build() {
    Column() {
      VerifyCodeComponentWithoutCursor()
    }
  }
}
@Component
struct VerifyCodeComponentWithoutCursor {
  @State codeText: string = "";
  @State focus: boolean = false
  @State inputController: inputMethod.InputMethodController = inputMethod.getController();
  private isAttached: boolean = false;
  private verifyCodeLength: number = 6;
  private codeIndexArray: Array<number> = Array.from([0, 1, 2, 3, 4, 5]);
  needFocusKey: string = 'textinput'

  onPageShow(): void {
    this.focus = true
  }

  async setAttachAndListener() {
    if (this.isAttached) {
      return;
    }
    let textConfig: inputMethod.TextConfig = {
      inputAttribute: {
        textInputType: inputMethod.TextInputType.NUMBER,
        enterKeyType: inputMethod.EnterKeyType.GO
      },
    };
    await this.inputController.attach(true, textConfig);
    this.isAttached = true;
    this.attachListener();
  }
  attachListener() {
    this.inputController.on("insertText", (text: string) => {
      if (this.codeText.length >= this.verifyCodeLength) {
        return;
      }
      this.codeText += text;
      if (this.codeText.length === this.verifyCodeLength) {
        console.info("VerifyCode: %{public}s", this.codeText);
      }
      console.info("VerifyCode [insert]: %{public}s", this.codeText);
    })
    this.inputController.on("deleteLeft", (length: number) => {
      this.codeText = this.codeText.substring(0, this.codeText.length - 1);
      console.info("VerifyCode [delete left]: %{public}s", this.codeText);
    })
  }
  
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进