具有动态主题值的 Google Recaptcha 组件 - Next.js

Byr*_*ron 5 reactjs next.js react-google-recaptcha

我正在react-google-recaptchaNext.js 上使用一个简单的联系表单。可以使用一个按钮来切换应用程序主题,该按钮触发一个函数,将“dark”作为类附加到 html 并在 localStorage 中添加一个变量。我如何才能更新验证码?

问题是要检查暗模式,我需要访问以window检查 html 附加类或localStorage检索我在主题开关上附加的暗模式值。这意味着我只能使用componentDidMount仅触发一次的生命周期方法。(SSR)

我需要一些可以在上述任何一个值发生更改并重新安装组件时动态注入主题字符串的东西。这是Captcha.jsx我要导入到我的contact.jsx页面中的组件。

import React, { Component } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';

export default class Captcha extends Component {
  constructor(props) {
    super(props);
    this.state = {
      theme: 'light',
    };
  }

  componentDidMount() {
    const darkmode = document.querySelector('html').classList.contains('dark');
    if (darkmode) {
      this.setState({ theme: 'dark' });
    } else {
      this.setState({ theme: 'light' });
    }
  }

  render() {
    return <ReCAPTCHA theme={this.state.theme} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

ReCAPTCHA 主题在硬刷新时发生变化,但在单击功能切换时不会发生变化,这会:root在发现 html 附加“深色”时使用选择器更改其他所有内容。

小智 0

这里有两件事要做。

首先,您需要重新安装 Recaptcha 组件。您可以使用该属性来执行此操作key,每次更改主题时提供一个新密钥将强制重新安装组件。

constructor() {
  super(props);
  this.state = {
    theme: 'light',
    key: 0
  };
}


componentDidMount() {
    const darkmode = document.querySelector('html').classList.contains('dark');
    if (darkmode) {
      this.setState({ theme: 'dark' });
    } else {
      this.setState({ theme: 'light' });
    }
    this.setState({ key: this.state.key++ }); 
  }

render() {
    return <ReCAPTCHA key={this.state.key} theme={this.state.theme} />;
  }
Run Code Online (Sandbox Code Playgroud)

其次,如果启用...禁用文件<React.StrictMode>中的index.js

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode> // delete or comment this line.
    <App />
  </React.StrictMode> // delete or comment this line.
);
Run Code Online (Sandbox Code Playgroud)