【问题标题】:Add a child `div` component on button click (ReactJS)在按钮单击时添加一个子 `div` 组件(ReactJS)
【发布时间】:2021-12-09 20:28:55
【问题描述】:

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

如果是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 吗?或者也欢迎任何其他方法。

【问题讨论】:

    标签: javascript html css reactjs bootstrap-4


    【解决方案1】:

    创建状态 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>
      );
    }
    
    
    

    【讨论】:

      【解决方案2】:

      类似于@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 或更改为null。使用按钮上的onClick 属性来打开和关闭网格视图。将状态值保留为布尔值,以便您可以直接使用三元运算符将 className 值分配给 div 来引用其真/假值。

      【讨论】:

      • 不错的方法,但无效的 div 组件也被视为col 类组件。谢谢你的帮助:)
      猜你喜欢
      • 2021-06-28
      • 2019-02-13
      • 2018-11-12
      • 2021-04-06
      • 2020-08-21
      • 1970-01-01
      • 2019-12-18
      • 2019-08-09
      • 1970-01-01
      相关资源
      最近更新 更多