react(ant.design)项目加载三方验证码TCaptcha.js的Demo

import React, { useState } from 'react';
import Script from 'react-load-script';
import { message } from "antd";

const DynamicScriptExample: React.FC<{}>=()=> {
  const [scriptLoaded,setScriptLoaded] = useState(false);


  const handleScriptError =()=> {
    message.error("组件加载失败")
  }

  const handleScriptLoad =()=> {
    setScriptLoaded(true)
  }

  const showView = () => {
    const captcha1 = new TencentCaptcha('youAppId', function(res) {
      // res(用户主动关闭验证码)= {ret: 2, ticket: null}
      // res(验证成功) = {ret: 0, ticket: "String", randstr: "String"}
      if(res.ret === 0){
        console.log(res.ticket)   // 票据
        console.log(res.randstr)   // 票据
      }
    });
    captcha1.show(); // 显示验证码
  }

    return (
      <>
        {scriptLoaded ? <button onClick={showView}>验证</button> : ''}
        
        <Script
          url="https://ssl.captcha.qq.com/TCaptcha.js"
          onError={handleScriptError}
          onLoad={handleScriptLoad}
        />

        <div>动态脚本引入状态:{scriptLoaded?'yes':'no'}</div>
      </>
    );
}

export default DynamicScriptExample;

  • 结果
    react(ant.design)项目加载三方验证码TCaptcha.js的Demo_第1张图片

你可能感兴趣的:(React,ant.design)