javascript - 上下文值不会在主题切换时更新
问题描述
所以我想根据存储在 Context 中的 localStorage 值和颜色进行主题化。问题是切换不会更新 ThemeContext 值,尽管它与布局状态绑定(恰好更新,但我想避免将调色板传递到整个树)。下面我将代码粘贴到提供的上下文中,切换按钮嵌套在代码中,但它与 React 文档中的内容没有什么不同:
//./comps/AdminLayout.js
import React, { Component } from 'react';
import Head from 'next/head';
import AdminNav from './AdminNav';
import ThemeContext from '../Utils/ThemeContext';
import themes from '../Utils/ColorPalette';
export default class extends Component {
static contextType = ThemeContext;
constructor(props) {
super(props);
this.state = {
theme: themes.light,
toggle: () => {
this.setState({
theme: (window.localStorage.theme === 'dark'
? themes.light
: themes.dark)
});
window.localStorage.theme = (window.localStorage.theme === 'dark' ? 'light': 'dark');
}
};
}
componentDidMount() {
window.localStorage.theme = 'light';
}
toggle() {
}
render() {
return (
<ThemeContext.Provider value={this.state}>
<div className="layout">
<style jsx global>{`
* {
box-sizing: border-box;
font-family: sans-serif;
margin: 0;
padding: 0;
}
html, body {
color: ${this.context.theme.primary};
box-sizing: inherit;
background: ${this.context.theme.background};
}
a {
color: inherit;
text-decoration: none;
}
button {
border: none;
}
`}</style>
<Head>
<title>{this.props.title} - Next Commerce</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</Head>
<AdminNav />
{this.props.children}
<style jsx>{`
.layout {
display: flex;
}
`}</style>
</div>
</ThemeContext.Provider>
);
}
}
//./comps/Utils/ThemeContext.js
import React from 'react';
import themes from './ColorPalette';
const ThemeContext = React.createContext({
theme : themes.light,
toggle: () => {}
});
export default ThemeContext;
//Button that is supposed to toggle theme - it changes AdminLayout's state
<ThemeContext.Consumer>
{({toggle}) => (
<button className="btn btn-theme" onClick={toggle}>Toggle theme</button>
)}
</ThemeContext.Consumer>
它与 Next 有某种关系还是我做错了什么?有什么解决办法吗?
只是为了澄清: ThemeContext.Consumer 也不起作用。
解决方案
推荐阅读
- reactjs - 安装第三方库后出现 React Native 错误
- react-native - React Native Slider - onValueChange 调用了太多次
- ruby - ruby 中区域之间的 S3 copy_object
- java - 在 NodeJS 和 Java 中计算 HMAC sha-512
- android - 如何在android avd虚拟设备中重新挂载只读系统文件夹
- python - 如何创建不需要导入的函数?(在 Python 中)
- r - “管道”形式的 R 传递函数
- icalendar - 重复规则 (RRULE RFC 5545 iCalendar)
- c - 这个函数如何在不使用任何指针的情况下工作?
- javascript - 如何在 Squarespace 模板中使用 Javascript 设置 H1 标签样式