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

相关推荐
沙尘暴炒饭17 小时前
用uniapp在微信小程序实现画板(电子签名)功能,使用canvas实现功能
微信小程序·小程序·uni-app
爱分享的程序员2 天前
小程序多线程实战
微信小程序
AALoveTouch2 天前
霸王茶姬微信小程序自动化签到系统完整实现&解析
微信小程序·自动化·notepad++
GalenWu2 天前
对象转换为 JSON 字符串(或反向解析)
前端·javascript·微信小程序·json
ᥬ 小月亮2 天前
Uniapp编写微信小程序,使用canvas进行绘图
微信小程序·uni-app·c#
BXCQ_xuan2 天前
uniapp小程序轮播图高度自适应优化详解
微信小程序·小程序·uni-app
艾路菲尔2 天前
微信小程序地图缩放scale隐性bug
微信小程序
前端开发小吴3 天前
微信小程序预览文件 兼容性苹果
微信小程序·小程序
Good Lucky3 天前
setData执行后操作方法-微信小程序
微信小程序·小程序·setdata
PyAIGCMaster3 天前
taro的学习记录
学习·taro