跳到主要内容

2 篇博文 含有标签「工具库」

查看所有标签

React项目中使用Google reCAPTCHA

· 阅读需 2 分钟
TransonQ
Front-end Engineer

一. 注册密钥​

首先,你需要在 Google reCAPTCHA 网站(https://www.google.com/recaptcha/admin/create)上注册并获取 API 密钥。完成注册后,你将获得一个 siteKey 和一个 secretKey,这些信息将用于在前端和后端验证 reCAPTCHA 响应。

二. 安装 reCAPTCHA 包​

npm
npm install react-google-recaptcha
yarn
yarn add react-google-recaptcha

三. 使用​

部分代码示意
import ReCAPTCHA from 'react-google-recaptcha'

const { REACT_APP_RECAPTCHA_KEY } = process.env // siteKey 配置进环境变量, 通常测试环境和正式环境是不一样的
...

const recaptchaRef = useRef(null) // 可以获取到 recaptcha 自带的方法
/**
* 验证用户是否完成了验证码测试的方法 execute:
* recaptchaRef.current.execute()
*
* 服务重新启动的方法 reset:
* recaptchaRef.current.reset();
*/

const [isVertified, setIsVertified] = useState(false) // 是否已经验证
const [recaptcha, setRecaptcha] = useState('') // 验证码存储, 如果遇到不想更新视图的场景, 考虑使用 useRef 储存

const onChange = (value) => {
// 拿到用户点击后的验证码, 通常需要后端接收这个验证码, 所以其一般是请求体的某个字段值
if (value) {
setIsVertified(true)
setRecaptcha(value)
}
}

...
return (
<>
<ReCAPTCHA
ref={recaptchaRef}
// size="invisible"
sitekey={REACT_APP_RECAPTCHA_KEY}
onChange={onChange}
/>
<Button disabled={!isVertified}>
Submit
</Button>
</>
)


react 实用工具UI库

· 阅读需 1 分钟
TransonQ
Front-end Engineer

React Hot Toast​

yarn add react-hot-toast
App.jsx
function App(){
return <><Toaster position="bottom-center"/></>
}
hotToast.ts
import { toast } from 'react-hot-toast'
type optionProps = {
error?: boolean
}

const color = {
critical: 'rgba(216, 44, 13, 1)', // --p-action-critical 错误色
default: 'rgba(32, 33, 35, 1)', // --p-surface-dark 默认黑色
}

export const hotToast = (msg: string, options?: optionProps) => {
toast(msg, {
style: {
borderRadius: '4px',
background: !options?.error ? color.default : color.critical,
color: '#fff',
},
})
}

使用
hotToast("提示信息")
hotToast("错误信息",{error:true})

Sonner​

yarn add sonner

用法同React Hot Toast

React Wrap Balancer​

yarn add react-wrap-balancer
使用方法
import Balancer from 'react-wrap-balancer'

// ...

<h1>
<Balancer>My Title</Balancer>
</h1>
多个组件可以共享逻辑
import { Provider } from 'react-wrap-balancer'

// ...

<Provider>
<App/>
</Provider>