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

相关推荐
MonkeyKing_sunyuhua2 小时前
微信小程序能不能获取物联网的上的设备数据
物联网·微信小程序·小程序
mg6682 小时前
微信小程序入门实例_____从零搭建你的第一个微信小程序
微信小程序·小程序
皮皮灬虾3 小时前
微信小程序下单页—地址列表页—新增地址页 页面交互
微信小程序·小程序·交互
源码_V_saaskw9 天前
宇鹿家政服务系统小程序ThinkPHP+UniApp
微信小程序·小程序·uni-app·微信公众平台
vvilkim10 天前
Taro 状态管理全面指南:从本地状态到全局方案
taro
Q_Q196328847510 天前
python基于微信小程序的广西文化传承系统
开发语言·spring boot·python·微信小程序·django·flask
kingbal10 天前
uniapp:微信小程序胶囊「复制链接」灰色处理
微信小程序·小程序·uni-app
知否技术11 天前
2025微信小程序开发实战教程(四)
前端·微信小程序
2501_9240641111 天前
微信小程序自动化测试方案实践过程 2025最新实践白皮书
微信小程序·小程序
Leisure -_-11 天前
【微信小程序修改首页顺序不生效】
微信小程序·小程序