如何创建动态添加输入字段

时间:2021-05-18 17:12:05

标签: javascript reactjs react-hooks

我正在尝试创建一个动态添加输入字段,当用户在输入中输入时,添加按钮可以点击。点击添加后会出现另一个输入框。

这是它的样子:

enter image description here

这是我实施的:

  const [inputs, setInputs] = useState(
    teamData.rules.map((value) => ({
      value,
      guid: uuidV4(),
    }))
  );

  const addInputs = (event) => {
    event.preventDefault();
    setInputs((inputs) => [
      ...inputs,
      {
        name: `rule_${inputs.length + 1}`,
        guid: uuidV4(),
      },
    ]);
  };
  const removeInputs = (index) => {
    const newList = inputs.filter((item, i) => index !== i);
    setInputs(newList);
  };
  const clearInput = (dataName) => {
    setUpdateTeamData((prevState) => {
      delete prevState[dataName];
      return {
        ...prevState,
      };
    });
  };

<div>
  {inputs?.map((data, idx) => {
    return (
      <div className="agreement-form-grid" key={data.guid}>
        <button
          type="button"
          className="agreement-remove-button"
          onClick={() => {
            removeInputs(idx);
            clearInput(`rule_${idx}`);
          }}
        >
          <Remove />
        </button>
        <input
          name={`rule_${idx}`}
          onChange={handleChange}
          placeholder={`Rule ${idx + 1}`}
          defaultValue={teamData.rules[idx]}
        />
      </div>
    );
  })}

enter image description here

如何实现第一张图的功能?

1 个答案:

答案 0 :(得分:1)

你需要两个变量。一个是存储添加规则列表的数组,第二个是用于保存尚未添加到数组中的规则值的字符串:

const [rules, setRules] = useState([{ value: "test", id: 0 }]);
  const [preAddedRule, setPreAddedRule] = useState("");

然后,通过依赖这些函数,您可以向变量添加和删除规则:

const handleRemove = (id) => {
    setRules(rules.filter((rule, i) => rule.id !== id));
  };
  const handleAdd = (id) => {
    setRules([...rules, { value: preAddedRule, id: rules.length }]);
    setPreAddedRule("");
  };
  const handleChange = (e) => {
    setPreAddedRule(e.target.value);
  };

记得把 preAddedRule 添加到数组后清除它的值,以便为接下来的规则做准备。

最后,显示您的所有规则、输入和按钮,如下所示:

{rules.map((el, i) => (
        <div>
          <input value={el.value} />
          <button onClick={() => handleRemove(el.id)}>delete</button>
        </div>
      ))}
      <input onChange={handleChange} value={preAddedRule} />
      <button onClick={() => handleAdd()}>Add</button>

sandbox