动态添加/删除表单输入 [英] Add/remove form inputs dynamically

查看:48
本文介绍了动态添加/删除表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 form ,其中有一个初始空的 input 字段,我想使用 Add 按钮进行克隆,并使用删除>删除一个.

I have a form with one initial empty input field that I want to clone using a Add button and to remove with a Remove one.

由于不建议对具有动态形式的键使用索引,因此我尝试使用 uniqid 模块.但是每次 state 更新时,键都会更新,而且我没有唯一的数据来标识表单的每个输入.我可以添加一些项目,但不能删除.

As it's not recommended to use index for the keys with dynamic forms, I tried to use uniqid module. But each time the state is updating, keys are renewed and I don't have unique data to identify each input of the form. I can add some items, but can't remove.

input 字段没有唯一值,没有 id ,该怎么办?

input fields have no unique values, no id, how can I do ?

const Form = () => {
  const update = e => {};
  const items = [{ content: "", color: "" }];

  return (
    <Fragment>
      {items.map((item, idx) => (
        <input
          htmlFor={`item_${idx}`}
          value={item.content}
          onChange={update("item", idx)}
        />
      ))}
      <button onClick={e => dispatch(add(idx))}>Add</button>
      <button onClick={e => dispatch(remove(idx))}>Remove</button>
    </Fragment>
  );

推荐答案

您可以简单地扩展现有的 items 以使其具有唯一的 id 属性-最简单的方法是,可以将最大使用的 id 的值分配给该属性,该值增加1-我想,对于大多数实际用例来说,它都能解决问题:

You may simply extend your existing items to have unique id property - at its very simplest, you may assign the value of maximum used id increased by 1 to that property - I guess, it'll do the trick for most of practical use cases:

const [inputs, setInputs] = useState([{id:0,value:''}]),
      onRowAdd = () => {
          const maxId = Math.max(...inputs.map(({id}) => id))
          setInputs([...inputs, {id:maxId+1, value:''}])
      }

有了它,您将拥有唯一的 id ,以便在删除行时将其定位:

With that, you'll have unique id to anchor to as you delete rows:

onRowRemove = idToDelete => setInputs(inputs.filter(({id}) => id != idToDelete))

以下是此概念的演示:

const { useState } = React,
      { render } = ReactDOM
      
const Form = () => {
  const [inputs, setInputs] = useState([{id:0,value:''}]),
        onInput = (id,value) => {
          const inputsCopy = [...inputs],
                itemToModify = inputsCopy.find(item => item.id == id)
          itemToModify.value = value
          setInputs(inputsCopy)
        },
        onRowAdd = () => {
          const maxId = Math.max(...inputs.map(({id}) => id))
          setInputs([...inputs, {id:maxId+1, value:''}])
        },
        onRowRemove = idToDelete => setInputs(inputs.filter(({id}) => id != idToDelete)),
        onFormSubmit = e => (e.preventDefault(), console.log(inputs))
  return (
    <form onSubmit={onFormSubmit} >
      {
        inputs.map(({id,value}) => (
          <div key={id}>
            <input 
              onKeyUp={({target:{value}}) => onInput(id,value)}
            />
            <input type="button" onClick={onRowAdd} value="Add" />
            <input type="button" onClick={() => onRowRemove(id)} value="Remove" />
          </div>
        ))
      }
      <input type="submit" value="Log Form Data" />
    </form>
  )
}

render (
  <Form />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

这篇关于动态添加/删除表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆