【问题标题】:React: Map over array and dynamically render a component in a specific divReact:映射数组并在特定 div 中动态渲染组件
【发布时间】:2022-01-25 10:54:02
【问题描述】:

可能我错过了一些非常简单的东西,但是:

我有一个数组:

const [weight, setWeight] = useState([]);

我想映射它以动态渲染组件:

const renderWeight = () => {
    weight.map((e) => {
      <Weight />;
    });
  };

我希望在单击提交按钮时发生这种情况,并且我希望组件在特定的 div 中呈现。 我找不到这样做的方法。

谢谢!

【问题讨论】:

  • 你能为此提供一个代码沙箱吗?

标签: javascript reactjs


【解决方案1】:

你需要返回映射数组

const renderWeight = () => {
   return weight.map((e) => {
      <Weight />;
    });
  };


注意:确保为每个渲染的组件分配一个键

【讨论】:

    【解决方案2】:

    您可以使用显示变量作为切换器来显示/隐藏这样的权重组件

    import React, { useState } from "react";
    
    const App = () => {
      const [weight, setWeight] = useState([1, 2, 3]);
      const [show, setShow] = useState(false);
    
      return (
        <div className="container">
          <div className="weight">{show && weight.map((e) => <Weight />)}</div>
          <button onClick={() => setShow(!show)}>Click to show/hide</button>
        </div>
      );
    };
    
    export default App;
    
    

    【讨论】:

      【解决方案3】:

      你必须退货。

      const [show ,setShow] = useState(false)
      
      const renderWeight = () => {
         return weight.map((e) => {
             return <Weight />;
          });
      };
      
        return (
        <>
        <button onClick={() => setShow(!show)}>Click to show/hide</button>
         {
          show?
             renderWeight():''
         }
        </>
      

      );

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-22
        • 2016-09-23
        • 1970-01-01
        • 2019-10-20
        • 2014-10-29
        • 2014-12-18
        • 2015-02-10
        相关资源
        最近更新 更多