【问题标题】:how to toggle between two css classes with react如何使用反应在两个 CSS 类之间切换
【发布时间】:2021-04-28 12:10:02
【问题描述】:

我正在尝试在暗模式和正常模式两个类之间切换。

这是原生 js 事件监听器

     const modeSwitch = document.querySelector('.mode-switch');

  modeSwitch.addEventListener('click', () => {
    document.documentElement.classList.toggle('dark');
    modeSwitch.classList.toggle('active');
  });

点击此按钮可在两种模式之间切换。我怎样才能通过反应实现这一目标

     const [active, setActive] = useState(false)

     const handleToggle = () => {
      setActive(!active)
     }

 return (
    <button className="mode-switch" title="Switch Theme" onClick={handleToggle}>
          <svg className="moon" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" width="24" height="24" viewBox="0 0 24 24">
            <defs></defs>
            <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
          </svg>
        </button>
)

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    在这种情况下,您可以使用useRef:

    const [active, setActive] = useState(false)
    const modeRef = useRef();
    
    const handleToggle = () => {
         modeRef.current.classList.toggle("dark")
    }
    
    return (
        <button ref={modeRef} className="mode-switch" title="Switch Theme" onClick={handleToggle}>
              <svg className="moon" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" width="24" height="24" viewBox="0 0 24 24">
                <defs></defs>
                <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"></path>
              </svg>
        </button>
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2014-01-26
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多