React SDK
CaptchaLa 验证码官方 React 组件 + Hook —— 已发布到 npm:@captcha-la/react。
在线 Demo
📦
demo-v1.captcha.la/react —— 可直接体验,含 4 种 product 模式。 源码:Captcha-La/react-example。
安装
bash
npm install @captcha-la/react
# 或
yarn add @captcha-la/react
# 或
pnpm add @captcha-la/reactPeer 依赖:react@^17 || ^18 || ^19、react-dom@^17 || ^18 || ^19。
快速上手
组件方式
tsx
import { Captchala } from '@captcha-la/react'
function App() {
return (
<Captchala
appKey="your-app-key"
product="popup"
onSuccess={(result) => console.log('pass_token:', result.token)}
onError={(err) => console.error(err)}
/>
)
}Hook 方式
tsx
import { useCaptchala } from '@captcha-la/react'
function LoginForm() {
const { ready, verify } = useCaptchala({
appKey: 'your-app-key',
product: 'bind',
action: 'login',
})
async function handleSubmit(e) {
e.preventDefault()
const result = await verify()
// result.token → 跟表单一起提交
}
return (
<form onSubmit={handleSubmit}>
<button type="submit" disabled={!ready}>登录</button>
</form>
)
}Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
appKey | string | 必填 | CaptchaLa 应用 key |
serverToken | string | - | 服务端签发的一次性 challenge token。当应用配置 server_token_required=true 时必填。 |
product | 'popup' | 'float' | 'embed' | 'bind' | 'popup' | 显示模式 |
action | string | 'default' | 业务场景标识 |
lang | string | 'zh-CN' | 语言代码 |
onSuccess | (result) => void | - | 验证成功回调 |
onError | (error) => void | - | 验证失败回调 |
onClose | () => void | - | 关闭回调 |
onReady | () => void | - | 就绪回调 |
className | string | - | 容器 class |
style | CSSProperties | - | 容器 inline style |
通过 ref 调用方法
tsx
import { useRef } from 'react'
import { Captchala, type CaptchalaRef } from '@captcha-la/react'
function App() {
const ref = useRef<CaptchalaRef>(null)
return (
<>
<Captchala ref={ref} appKey="your-app-key" />
<button onClick={() => ref.current?.verify()}>触发验证</button>
</>
)
}| 方法 | 说明 |
|---|---|
verify() | 手动触发验证 |
reset() | 重置验证码状态 |
destroy() | 销毁验证码实例 |
bindTo(selector) | 绑定到指定元素(仅 bind 模式) |
setLang(lang) | 原地切换语言 |
生产环境:serverToken 模式
tsx
import { useState, useEffect } from 'react'
import { Captchala } from '@captcha-la/react'
function LoginPage() {
const [token, setToken] = useState<string>()
useEffect(() => {
fetch('/api/captcha-token') // 你自己的后端
.then((r) => r.json())
.then((d) => setToken(d.server_token))
}, [])
if (!token) return <div>Loading…</div>
return (
<Captchala
serverToken={token}
appKey="pk_your_public_app_key"
action="login"
onSuccess={(r) => console.log('pass_token:', r.token)}
/>
)
}完整契约见 API Reference。