简体   繁体   English

如何根据本地存储中的数据切换主题

[英]How do I switch my theme based on data from local storage

My theme settings always revert to the default theme on page refresh despite reading the theme settings from local storage 尽管从本地存储中读取主题设置,但我的主题设置始终会恢复为页面刷新时的默认主题

Here is my code for the theme implementation: 这是我的主题实现代码:

green.addEventListener('click', () => {
  if (localStorage.getItem('theme') != 'green') {
    localStorage.setItem('theme', 'green');
  }
  main.classList.add(localStorage.getItem('theme'));
});
yellow.addEventListener('click', () => {
  if (localStorage.getItem('theme') !== 'yellow') {
    localStorage.setItem('theme', 'yellow');
  }
  main.className = localStorage.getItem('theme');
});
purple.addEventListener('click', () => {
  if (localStorage.getItem('theme') !== '') {
    localStorage.setItem('theme', '');
  }
  main.className = localStorage.getItem('theme');
});

I've checked the localStorage and the theme values are stored 我检查了localStorage并存储了主题值

In your Initial class instead of setting it to empty, set the local storage to the default theme and read the theme value from local storage in your initial class. 在Initial类中,不要将其设置为空,将本地存储设置为默认主题,并从初始类的本地存储中读取主题值。 So that on page reload also you will be reading the theme from the local storage and it will be set already with the custom theme. 因此,在页面重新加载时,您将从本地存储中读取主题,并且将使用自定义主题进行设置。

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

相关问题 如何在反应 typescript 中呈现本地存储中的数据? - How do i render data from local storage in react typescript? 如何从 Django 视图中的本地存储访问数据? - How do I access data from local storage in Django views? 如何根据本地存储中的变量快速排序? - How do I quicksort something based on its variable in local storage? 如何使用本地存储让我的文本输入字段记住以前输入的数据? - How do I get my text input field to remember previously entered data by using local storage? 如何使搜索功能通过我的 html 表运行,由本地存储制成? - How do I make a search function that runs through my html table, made from local storage? 如何使用来自本地存储的令牌发出发布请求 - How do i make a post request with my token coming from local storage 如何将 redux state 与本地存储保持一致 - How do I persist my redux state with local storage 如何将我的注册详细信息存储在本地存储中? - How do i store my registration details in local storage? 如何将我的数据保存在本地存储中? - How can I save my data in the local storage? 如何从本地存储中获取特定的ID数据,以便使用jquery在表单中进行编辑 - How do I get a particular Id data from local Storage for editing in form using jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM