【问题标题】:Next.js toggle display of a div tagNext.js 切换显示 div 标签
【发布时间】:2020-03-30 21:12:28
【问题描述】:

代码

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 标签应该会显示,如果我再次单击它会被隐藏等等)。


现实

变量showMe 似乎发生了变化,但div 标记并未跟随更新并保持隐藏状态。

注意:如果有任何改变,我将使用 next.js。

【问题讨论】:

标签: javascript reactjs next.js


【解决方案1】:

showMe 需要是一个状态变量,以便 React 知道在 showMe 更改时重新渲染组件。我会读到这个:https://reactjs.org/docs/hooks-state.html

下面的代码应该可以工作(注意showMe 是如何替换为对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/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

useState返回一个长度为2的数组。使用数组解构,我们将返回数组的第一个元素设置为showMe,将返回数组的第二个元素设置为setShowMe

【讨论】:

  • 非常感谢!我对 [showMe, setShowMe] 这两个括号的表示法有点困惑
  • 啊,好的。谢谢!
  • 快速提问,为什么我必须使用import { useState } from "react"; 而不是import useState from "react"; 才能使用useState
  • react 的默认导出是我们在执行import React from "react" 时将其命名为React 的对象。 React 有一个属性useState,所以如果我们愿意,我们可以使用React.useState(false)。我会查看更多详细信息:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
猜你喜欢
  • 2014-01-26
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多