繁体   English   中英

如何使用React动态更改google recaptcha语言

[英]How do I dynamically change google recaptcha language using React

我正在使用react-google-recaptcha

我想在加载此组件时动态更改recaptcha元素。

要求:1。必须采取新道具并更改语言2.在卸载和重新安装组件时,还应该渲染新语言

  • 在卸载时清除谷歌recaptcha的全球价值。
  • 每当道具改变时,强制重新开始重新安装
  • 这两者的结合

window.recaptchaOptions = { removeOnUnmount: true }未正确删除recaptcha。

预期:recaptcha将重新安装并将其语言更改为所选语言。

实际:Recaptcha将使用相同的语言重新安装。

解:

  1. 在mount上动态导入react-google-recaptcha

  2. 在unMount上删除window.grecaptcha&window.recaptchaOptions

  3. 在更新结合步骤1和2

 export default class ReCaptchaValidation extends React.Component<Props> { static defaultProps = { handleChange: null, lang: 'en' } state = { Recaptcha: null } componentDidMount (): void { this.importRecaptcha() } importRecaptcha = async () => { const { lang } = this.props this.setState({ Recaptcha: null }) delete window.recaptchaOptions delete window.grecaptcha window.recaptchaOptions = { lang, useRecaptchaNet: false, removeOnUnmount: false } const { default: Recaptcha } = await import('react-google-recaptcha') this.setState({ Recaptcha }) } componentWillUnmount () { delete window.recaptchaOptions delete window.grecaptcha } componentDidUpdate (prevProps: Readonly<P>): void { if (prevProps.lang !== this.props.lang) { this.importRecaptcha() } } render () { const { apiKey, className, handleChange, lang } = this.props const { Recaptcha } = this.state return ( <div> {Recaptcha && ( <Recaptcha sitekey={apiKey} size={'normal'} onChange={handleChange} /> )} </div> ) } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM