taro中使用captcha

引入小程序组件

ts 复制代码
// src/app.config.ts
export default {
  ...
  plugins: {
    captcha: {
      version: '2.1.2',
      provider: 'wx2fe8d9a3cb888a99',
    },
  },
  ...
};

声明组件

ts 复制代码
// src/app.config.ts
export default {
  ...
  usingComponents: {
      "t-captcha": "plugin://captcha/t-captcha"
  },
  ...
};

ts 复制代码
// src/pages/xxx/index.config.ts
export default {
  ...
  usingComponents: {
      "t-captcha": "plugin://captcha/t-captcha"
  },
  ...
};

注意:页面中或者全局声明组件二选一,一般情况下在页面中引入。

demo

tsx 复制代码
import { getCurrentInstance } from '@tarojs/taro';
import { forwardRef, useImperativeHandle } from 'react';

export type CaptchaRef = {
  open: () => void;
};

type CaptchaProps = {
  success: () => void;
  onError: () => void;
};

const Captcha = forwardRef<CaptchaRef, CaptchaProps>((props, ref) => {
  const { page } = getCurrentInstance();

  const handlerOpen = () => {
    const captcha: any = page?.selectComponent?.('#captcha');
    try {
      captcha?.show();
    } catch (error) {
      captcha?.refresh();
    }
  };

  useImperativeHandle(ref, () => ({
    open: handlerOpen,
  }));

  const handlerVerify = (ev) => {
    if (ev.detail.ret === 0) {
      props.success?.();
    } else {
      props.onError?.();
    }
  };

  return (
    <t-captcha
      id="captcha"
      onVerify={handlerVerify}
      appId={process.env.CAPTCHA_APP_ID}
    />
  );
});

export default Captcha;

global.d.ts配置

ts 复制代码
// types/global.d.ts
declare global {
  namespace JSX {
    interface IntrinsicElements {
      't-captcha': React.DetailedHTMLProps<
        React.HTMLAttributes<HTMLElement>,
        HTMLElement
      > & {
        appId?: string;
        onVerify?: (e: CustomEvent<{ ret: any; ticket: string }>) => void;
      };
    }
  }
}

使用ts后再使用小程序原生组件就会变得麻烦。

相关推荐
爬坑的小白1 小时前
微信小程序拉起支付
微信小程序·小程序
humors2213 小时前
Deepseek工具:H5+Vue 项目转微信小程序报告生成工具
前端·vue.js·微信小程序·h5·工具·报告
毕设源码-钟学长5 小时前
【开题答辩全过程】以 基于微信小程序的蓝鲸旧物回收系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
sheji34167 小时前
【开题答辩全过程】以 基于微信小程序的考研服务平台为例,包含答辩的问题和答案
微信小程序·小程序
AnalogElectronic8 小时前
uniapp学习1,hello world 项目,打包到微信小程序,贪吃蛇小游戏
学习·微信小程序·uni-app
人还是要有梦想的1 天前
如何开发微信小程序
微信小程序·小程序·notepad++
inksci2 天前
Js生成安全随机数
前端·微信小程序
azhou的代码园2 天前
基于SpringBoot+微信小程序的图片识别科普系统
spring boot·后端·微信小程序
志遥2 天前
我把 Sentry 接进了 7 端小程序:从异常捕获、Breadcrumb 到 Source Map 定位
微信小程序·监控
云起SAAS2 天前
在线客服系统源码 | 支持PC管理端+H5访客端+实时聊天
微信小程序·ai编程·看广告变现轻·在线客服系统源码