我正在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)