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

问题描述

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>
    </>
  );
}


期望

div标记应切换可见性(例如,如果单击一次按钮,则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).

看来变量showMe发生了变化,但是div标记没有跟随更新,而是保持隐藏状态.

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

注意:如果更改后,我正在使用next.js.

推荐答案

showMe必须是一个状态变量,以便当showMe更改时,React知道重新渲染组件.我将阅读以下内容: https://reactjs.org/docs/hooks-state.html

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

下面的代码应该起作用(注意如何用useState调用替换showMe).

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>
    </>
  );
}

括号表示法const [showMe, setShowMe] = useState(false);是数组解构: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

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返回长度为2的数组.使用数组解构,我们将返回数组的第一个元素设置为showMe,并将返回数组的第二个元素设置为setShowMe.

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标签的显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 07:50