首页 > 解决方案 > 具有动态主题值的 Google Recaptcha 组件 - Next.js

问题描述

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

问题是检查我需要访问的暗模式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} />;
  }
}

ReCAPTCHA 主题在硬刷新时更改,但在单击功能切换时不会更改,这会:root在找到附加到 html 的“暗”时使用选择器更改所有其他内容。

标签: reactjsnext.jsreact-google-recaptcha

解决方案


推荐阅读