You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于React实现点击按钮动态添加输入框功能

解决React中按按钮点击顺序生成对应输入框的问题

Got it, let's fix this up properly! The issue here is that your current code has hardcoded input fields instead of dynamically rendering them based on the order of button clicks. Since you're using React, we'll leverage state to track the sequence of inputs we need to create—this is the standard React approach for dynamic UI changes.

修改思路

  1. 使用React的useState钩子维护一个数组,记录用户点击按钮的顺序(每个元素标记是"Food Category"还是"Food Name"输入框)。
  2. 给两个按钮绑定点击事件,点击时向数组中添加对应的输入类型。
  3. 遍历这个数组,动态渲染出对应顺序的输入框。

修改后的完整代码

import { useState } from 'react'; // 别忘了引入useState!

function NewMenu() {
  // 用state存储输入框的顺序,每个元素是输入类型标识
  const [menuInputs, setMenuInputs] = useState([]);

  // 添加分类输入框的函数
  const addFoodCategory = () => {
    setMenuInputs(prev => [...prev, 'category']);
  };

  // 添加名称输入框的函数
  const addFoodName = () => {
    setMenuInputs(prev => [...prev, 'name']);
  };

  return (
    <div>
      <h1>Create New Menu</h1>
      <button onClick={addFoodCategory}>Add Food Category</button>
      <button onClick={addFoodName}>Add Food Name</button>
      <div id='menuItems'>
        {/* 遍历state数组,动态渲染输入框 */}
        {menuInputs.map((type, index) => (
          <input
            key={index} // 用索引作为key(如果后续要支持删除,建议用唯一ID)
            type='text'
            placeholder={type === 'category' ? 'Food Category' : 'Food Name'}
          />
        ))}
      </div>
    </div>
  );
}

关键细节说明

  • 状态管理:menuInputs数组会记录每一次按钮点击的顺序,比如用户先点"Add Food Category",再点两次"Add Food Name",数组就会是['category', 'name', 'name'],渲染出来的输入框顺序完全匹配。
  • 函数式更新:我们用prev => [...prev, 'type']的方式更新状态,这能确保我们总是基于最新的状态来添加新元素,避免状态更新的竞态问题。
  • 动态渲染:通过map遍历数组,根据每个元素的type值设置对应的placeholder,实现了按点击顺序生成输入框的需求。

如果后续需要支持删除输入框的功能,只需要给每个输入框添加删除按钮,点击时从menuInputs数组中移除对应元素即可——这也是React状态驱动UI的优势,所有UI变化都通过修改状态来实现。

内容的提问来源于stack exchange,提问作者Samet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:42:37