javascript - 在 React JS 中使用 onClick 复制组件
问题描述
假设我有一个看起来像这样的应用程序:
<>
<Component />
<button>Add New Component</button>
</>
我怎样才能使它每次单击按钮时都会<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,并可能将其与更多数据打包为对象,但您明白了。
推荐阅读
- android - 任务:app:processDebugResources FAILED>..executing com.android.build.gradle.internal.tasks.Workers$ActionFacade > 类太大:sample/co/us/R$id
- jenkins - 如何从管道运行参数化作业?
- c++ - 用传递的数组构造结构
- python - Python JSON字符串到表格格式
- laravel - 方法 Illuminate\Routing\Route::getPath 不存在
- sql - 将列名存储在 SQL 变量中以用于 SSRS 中的动态钻取报告
- sql-server - 如何在 SQL Server 中使用 DateTime 进行模式查找
- firebase - 从 Firebase 远程配置中获取统一广告 ID 的问题
- node.js - Express:避免未定义/未使用的路线
- c# - 无法使用 System.Text.Json 反序列化 DateTime、Guid 或 Enum