将Bootstrap Switch组件设置为' checked'如果模式是黑暗的

发布于 2025-01-24 14:39:04 字数 1255 浏览 0 评论 0原文

我在LocalStorage中的Web应用程序中有一个主题,如果将模式设置为“ Dark”或未经选中(如果模式为“ Light”),则将检查值添加到开关组件中。 但是,当我将主题设置为“黑暗”并刷新页面时,开关会自动转动到未检查时,该如何解决? 有代码的下方:

import React, { useState,useEffect } from 'react';
import useTheme from '../custom/useTheme';

export default function Switch() {
  const[active,setActive] = useState(false);

  function handleTheme(){
    if(active === false){
      // Dark mode
      useTheme(true);
      setActive(true);

      localStorage.setItem('mode','dark');
    }else if(active === true){
      // Light mode
      useTheme(false);
      setActive(false);
      localStorage.setItem('mode','light');
    }
  };
  
  return (
    <div id='switchBox' className='form-check form-switch'>
      <input
      id="switch" 
      role="switch"
      // checked
      value={active}
      type="checkbox"
      onClick={()=> handleTheme()}
      className="form-check-input shadow-sm"
      />
      <label
      className='ms-1'
      htmlFor='switch'
      >Dark</label>
    </div>
  )
};

这就是它的外观,黑暗主题已经打开,但是开关不受限制。

I have a theme for my web App in my localStorage and I want to add the checked value to the Switch component if the mode is set to 'dark',or unchecked, if the mode is 'light'.
However, when I set the theme to 'dark' and refresh the page the switch turn automatically to unchecked, how can I fix that?
Below there is the code:

import React, { useState,useEffect } from 'react';
import useTheme from '../custom/useTheme';

export default function Switch() {
  const[active,setActive] = useState(false);

  function handleTheme(){
    if(active === false){
      // Dark mode
      useTheme(true);
      setActive(true);

      localStorage.setItem('mode','dark');
    }else if(active === true){
      // Light mode
      useTheme(false);
      setActive(false);
      localStorage.setItem('mode','light');
    }
  };
  
  return (
    <div id='switchBox' className='form-check form-switch'>
      <input
      id="switch" 
      role="switch"
      // checked
      value={active}
      type="checkbox"
      onClick={()=> handleTheme()}
      className="form-check-input shadow-sm"
      />
      <label
      className='ms-1'
      htmlFor='switch'
      >Dark</label>
    </div>
  )
};

That's how it looks, the Dark theme is on, but the Switch is unchecked.

Dark mode on, but Switch turn off

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

×眷恋的温暖 2025-01-31 14:39:04

您可以使用使用用空数组来实现此目标。当组件渲染时,这将触发一次逻辑。在内部,您可以检索先前保存的模式属性,并使用它来设置当前会话状态:

useEffect(() => {
    const isLight = localStorage.getItem('mode');
    if (isLight !== undefined) setActive(isLight);
}, [])

You can achieve this by using useEffect hook with an empty array. This will trigger the logic inside once when the component is rendered. Inside you can retrieve the previously saved mode property and use it to set the current session state:

useEffect(() => {
    const isLight = localStorage.getItem('mode');
    if (isLight !== undefined) setActive(isLight);
}, [])
无戏配角 2025-01-31 14:39:04

正如上面的答案所述,状态存储在内存中,并在您刷新页面时会丢失。尽管您的解决方案将主题状态持续到LocalStorage,但您还需要将Usestate的初始值设置为存储在LocalStorage 中的值,以便在刷新后显示正确的状态。您可以尝试这样的事情:

const[active, setActive] = useState(false)

// Get stored data from local storage if available on first render
useEffect(() => {
    // Get stored theme mode and set it in state manager
    const storedTheme = localStorage.getItem('mode')
    if(storedTheme) {
        setActive(storedTheme)
    }
}, [])

通过将空数组作为第二个参数以使用效果,这只会在初始渲染上运行。
有关使用效果的更多信息,请参阅REECT文档: https://reactjs.s.org/docs/钩 - 效果.html

As the above answer mentions, state is stored in memory and is lost when you refresh the page. While your solution persists the theme state to localstorage you also need to set the initial value of useState to the value stored in localstorage in order to display the correct state after refresh. You can try something like this:

const[active, setActive] = useState(false)

// Get stored data from local storage if available on first render
useEffect(() => {
    // Get stored theme mode and set it in state manager
    const storedTheme = localStorage.getItem('mode')
    if(storedTheme) {
        setActive(storedTheme)
    }
}, [])

By passing an empty array as the second parameter to useEffect this will only run on the initial render.
For more information on useEffect, refer to the React docs: https://reactjs.org/docs/hooks-effect.html

神经暖 2025-01-31 14:39:04

我使用与三元运营商进行检查解决了,在我想...
那是正确的解决方案!

  <input
  id="switch" 
  role="switch"
  checked={localStorage.getItem('mode') === 'dark'?(true):(false)}
  value={active}
  type="checkbox"
  onClick={()=> handleTheme()}
  className="form-check-input shadow-sm"
  />

I solved using checked with a ternary operator, giving to it the True or False value in the case I want to...
That's the correct solution !

  <input
  id="switch" 
  role="switch"
  checked={localStorage.getItem('mode') === 'dark'?(true):(false)}
  value={active}
  type="checkbox"
  onClick={()=> handleTheme()}
  className="form-check-input shadow-sm"
  />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文