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后再使用小程序原生组件就会变得麻烦。

相关推荐
m0_726365835 小时前
2025年微信小程序开发:趋势、最佳实践与AI整合
人工智能·微信小程序·notepad++
gurenchang7 小时前
动态设置微信小程序页面标题(navigationBarTitleText属性)
微信小程序·小程序
Emma歌小白8 小时前
ReferenceError: wx is not defined
微信小程序
老李不敲代码11 小时前
榕壹云健身预约系统:多门店管理的数字化解决方案(ThinkPHP+MySQL+UniApp实现)
mysql·微信小程序·uni-app·php·软件需求
幽络源小助理12 小时前
SpringBoot+Vue+微信小程序校园自助打印系统
java·spring boot·微信小程序·小程序·vue
程序员陆通14 小时前
Cursor + Claude 4:微信小程序流量主变现开发实战案例
微信小程序·小程序
程序员小刘1 天前
【HarmonyOS 5】鸿蒙Taro跨端框架
华为·harmonyos·taro
汤姆yu1 天前
基于微信小程序的垃圾分类系统
微信小程序·小程序
Mr.Liu61 天前
小程序32-简易双向数据绑定
前端·微信小程序·小程序
Mr.Liu62 天前
小程序33-列表渲染
前端·微信小程序·小程序