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

相关推荐
文心快码BaiduComate1 小时前
用Comate Zulu开发一款微信小程序
前端·后端·微信小程序
Emma歌小白2 天前
如何首次运行小程序后端
微信小程序
赣州云智科技的技术铺子2 天前
【一步步开发AI运动APP】十二、自定义扩展新运动项目1
微信小程序·小程序·云开发·智能小程序
海绵宝宝不喜欢侬3 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
亮子AI3 天前
【小程序】微信小程序隐私协议
微信小程序·小程序
毕设源码-钟学长3 天前
【开题答辩全过程】以 “旧书驿站”微信小程序的设计与开发为例,包含答辩的问题和答案
微信小程序·小程序
nodcloud4 天前
点可云进销存商城如何部署在微信小程序
微信小程序·小程序
项目題供诗5 天前
微信小程序开发教程(八)
微信小程序·小程序
拼图2095 天前
微信小程序——云函数【使用使用注意事项】
微信小程序·小程序
Q_Q5110082855 天前
springboot+python+uniapp基于微信小程序的旅游服务系统景点信息展示 路线推荐 在线预约 评论互动系统
spring boot·python·微信小程序·django·flask·uni-app