在单击按钮时添加一个子“div”组件(ReactJS)

Add a child `div` component on button click (ReactJS)

我正在尝试通过单击按钮添加子 div 组件(div-col inside div-row)。像这里一样,我试图将卡片的方向从网格更改为列表视图。我在这里使用 bootstrap 内置 class。

如果是grid view,那么

<div className="row">
  {notes.map((item, key) => {
    return <Noteitem  />;
  })}
</div>

如果 listview 按钮被点击

<div className="row">
  <div className="col"> 
    {notes.map((item, key) => {
      return <Noteitem  />;
    })}
  </div> 
</div> 

我需要分别使用 return 和 DOM 吗??或者也欢迎使用任何其他方法。

创建状态 myView 并将默认设置为 'GridView' listView 按钮被点击,setState 为 'ListView'.

使用这个状态,渲染得像

{
  myView === "GridView" ? (
    <div className="row">
        {notes.map((item, key) => {
          return <Noteitem />;
        })}
    </div>
  ) : (
    <div className="row">
      <div className="col">
        {notes.map((item, key) => {
          return <Noteitem />;
        })}
      </div>
    </div>
  );
}


类似于@Bee 的回答,但更加简洁和充实:

const [grid, setGrid] = useState(false)

return (
    <button onClick={() => setGrid(!grid)} />
    <div className="row">
       <div className={grid ? "col" : ""}> 
         {notes.map((item, key) => {
            return <Noteitem  />;
         })}
      </div> 
    </div>
)

说明

您将 div 元素保留在 DOM 上,只需将 className 更改为 col 或从 col 更改为无效。使用按钮上的 onClick 属性来打开和关闭网格视图。将状态值保留为布尔值,以便您可以直接使用三元运算符引用其 truthy/falsey 值,将 className 值分配给 div.