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

相关推荐
咖啡の猫20 小时前
微信小程序案例 - 自定义 tabBar
微信小程序·小程序·notepad++
咖啡の猫21 小时前
微信小程序全局数据共享
微信小程序·小程序
桐溪漂流21 小时前
微信小程序cli脚本预览上传
微信小程序·小程序
咖啡の猫21 小时前
微信小程序使用 npm 包
微信小程序·小程序·npm
东东5162 天前
xxx食堂移动预约点餐系统 (springboot+微信小程序)
spring boot·微信小程序·小程序·毕业设计·个人开发·毕设
韩立学长2 天前
【开题答辩实录分享】以《智慧校园平台微信小程序》为例进行选题答辩实录分享
spring boot·微信小程序·小程序
h_65432102 天前
微信小程序:按顺序一张图片加载完后,再加载另一张
微信小程序·小程序
qq_316837753 天前
uniapp打包微信小程序使用插件
微信小程序·小程序·uni-app
不爱学习小趴菜4 天前
uniapp微信小程序无法屏蔽右上角胶囊按钮(...)问题解决方案
微信小程序·小程序·uni-app
plmm烟酒僧4 天前
《微信小程序demo开发》第一部分-编写页面逻辑
javascript·微信小程序·小程序·html·微信开发者工具·小程序开发