Next.js 切换显示 div 标签 [英] Next.js toggle display of a div tag

查看:15
本文介绍了Next.js 切换显示 div 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Code

export default function Header(){
  let showMe = false;
  function toggle(){
    showMe = !showMe;
  }
  return (
    <>
      <button onClick={toggle}>Toggle Subjects</button>
      {/*The bottom code should toggle on and off when the button is pressed*/}
      <div style={{
        display: showMe?"block":"none"
      }}>
        This should toggle my display
      </div>
    </>
  );
}


Expectation

The div tag should toggle in visibility (For example, if I clicked on the button once, the div tag should show up, and if I clicked on it again it would be hidden and so on).


Reality

It appears the variable showMe changes however the div tag does not follow with the updates and remains hidden.

NOTE: I am using next.js if that changes anything.

解决方案

showMe needs to be a state variable so that React knows to rerender the component when showMe changes. I'd read this: https://reactjs.org/docs/hooks-state.html

The code below should work (note how showMe is replaced with a call to useState).

export default function Header(){
  const [showMe, setShowMe] = useState(false);
  function toggle(){
    setShowMe(!showMe);
  }
  return (
    <>
      <button onClick={toggle}>Toggle Subjects</button>
      {/*The bottom code should toggle on and off when the button is pressed*/}
      <div style={{
        display: showMe?"block":"none"
      }}>
        This should toggle my display
      </div>
    </>
  );
}

The bracket notation const [showMe, setShowMe] = useState(false); is Array Destructuring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

useState returns an array of length 2. Using array destructuring, we set the first element of the returned array to showMe and the second element of the returned array to setShowMe.

这篇关于Next.js 切换显示 div 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆