--- title: React SDK --- # React SDK CaptchaLa 验证码官方 React 组件 + Hook —— 已发布到 npm:[`@captcha-la/react`](https://www.npmjs.com/package/@captcha-la/react)。 ## 在线 Demo ::: tip 📦 [demo-v1.captcha.la/react](https://demo-v1.captcha.la/react/) —— 可直接体验,含 4 种 product 模式。 源码:[Captcha-La/react-example](https://github.com/Captcha-La/react-example)。 ::: ## 安装 ```bash npm install @captcha-la/react # 或 yarn add @captcha-la/react # 或 pnpm add @captcha-la/react ``` Peer 依赖:`react@^17 || ^18 || ^19`、`react-dom@^17 || ^18 || ^19`。 ## 快速上手 ### 组件方式 ```tsx import { Captchala } from '@captcha-la/react' function App() { return ( 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 (
) } ``` ## 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(null) return ( <> ) } ``` | 方法 | 说明 | |------|------| | `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() useEffect(() => { fetch('/api/captcha-token') // 你自己的后端 .then((r) => r.json()) .then((d) => setToken(d.server_token)) }, []) if (!token) return
Loading…
return ( console.log('pass_token:', r.token)} /> ) } ``` 完整契约见 [API Reference](/zh-CN/api-reference)。 ## 链接 - [npm](https://www.npmjs.com/package/@captcha-la/react) · [GitHub](https://github.com/Captcha-La/react) · [example](https://github.com/Captcha-La/react-example) - [Web SDK 总览](/zh-CN/web-sdk) · [API Reference](/zh-CN/api-reference)