--- title: React SDK --- # React SDK CaptchaLa CAPTCHA 的官方 React 元件 + hook — 發佈於 [`@captcha-la/react`](https://www.npmjs.com/package/@captcha-la/react)。 ## 線上範例 ::: tip 📦 [demo-v1.captcha.la/react](https://demo-v1.captcha.la/react/) — 可執行的範例,涵蓋四種產品模式。 原始碼:[Captcha-La/react-example](https://github.com/Captcha-La/react-example)。 ::: ## 安裝 ```bash npm install @captcha-la/react # or yarn add @captcha-la/react # or pnpm add @captcha-la/react ``` Peer dependencies:`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 → submit with the form } return (
) } ``` ## Props | Prop | 型別 | 預設值 | 說明 | |------|------|---------|-------------| | `appKey` | `string` | *必填* | CaptchaLa 應用程式金鑰 | | `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 樣式 | ## 方法(透過 `ref`) ```tsx import { useRef } from 'react' import { Captchala, type CaptchalaRef } from '@captcha-la/react' function App() { const ref = useRef(null) return ( <> ) } ``` | 方法 | 說明 | |--------|-------------| | `verify()` | 觸發驗證 | | `reset()` | 重置 CAPTCHA 狀態 | | `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') // your own backend .then((r) => r.json()) .then((d) => setToken(d.server_token)) }, []) if (!token) return
Loading…
return ( console.log('pass_token:', r.token)} /> ) } ``` 完整的後端合約請見 [API 參考](/zh-TW/api-reference)。 ## 相關連結 - [npm](https://www.npmjs.com/package/@captcha-la/react) · [GitHub](https://github.com/Captcha-La/react) · [範例](https://github.com/Captcha-La/react-example) - [Web SDK 概覽](/zh-TW/web-sdk) · [API 參考](/zh-TW/api-reference)