首页 > 解决方案 > 在 React JS 中使用 onClick 复制组件

问题描述

假设我有一个看起来像这样的应用程序:

<>
  <Component />
  <button>Add New Component</button>
</>

我怎样才能使它每次单击按钮时都会<Component />附加一个新按钮?这与我们显示或隐藏组件时的条件渲染无关,而是关于添加无限数量的新组件的可能性。你有什么想法?

标签: javascriptreactjsstatereact-component

解决方案


一般的工作流程是将组件数据(或只是标识符)存储在状态数组中。然后,您映射数组以呈现您的Component列表。该按钮将新的标识符/数据集添加到数组中。

const App = () => {
  const [list, setList] = useState([0]);

  const addComponent = () => {
    setList([...list, list.length]);
  };

  return (
    <>
      {list.map(id => <Component key={id} />)}
      <button onClick={addComponent}>Add New Component</button>
    </>
  )
};

这是一个非常简单的例子。实际上,您可能希望为键分配唯一的 ID,并可能将其与更多数据打包为对象,但您明白了。


推荐阅读