简体   繁体   English

当用户单击react.js中的按钮时如何动态添加输入字段

[英]how to add input field dynamically when user click on button in react.js

I have two Question ->我有两个问题->

First one is I want to add user input field dynamically when user click "+" button in react.js.第一个是我想在用户单击 react.js 中的“+”按钮时动态添加用户输入字段。 And if user click more times then more number of field add to the form.如果用户点击更多次,那么更多数量的字段会添加到表单中。 How to do this in react.js?如何在 react.js 中做到这一点?

Second one when user change its value I want to store their corresponding value of each input field into my component state variable.第二个当用户更改其值时,我想将每个输入字段的相应值存储到我的组件 state 变量中。 Now here how I add their value, what data structure I use array or object or something else?现在在这里我如何添加它们的值,我使用数组或 object 或其他什么数据结构? and how?如何?

function App() {
  const inputArr = [
    {
      type: "text",
      id: 1,
      value: ""
    }
  ];

  const [arr, setArr] = useState(inputArr);

  const addInput = () => {
    setArr(s => {
      return [
        ...s,
        {
          type: "text",
          value: ""
        }
      ];
    });
  };

  const handleChange = e => {
    e.preventDefault();

    const index = e.target.id;
    setArr(s => {
      const newArr = s.slice();
      newArr[index].value = e.target.value;

      return newArr;
    });
  };

  return (
    <div>
      <button onClick={addInput}>+</button>
      {arr.map((item, i) => {
        return (
          <input
            onChange={handleChange}
            value={item.value}
            id={i}
            type={item.type}
            size="40"
          />
        );
      })}
    </div>
  );
}

I would set a counter and increase it with each click of a button.我会设置一个计数器并在每次单击按钮时增加它。 I would map the counter numbers into an array and loop over creating new input elements.我会将 map 计数器编号放入一个数组并循环创建新的输入元素。

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [counter, setCounter] = useState(0);

  const handleClick = () => {
    setCounter(counter + 1);
    console.log(counter);
  };
  return (
    <div className="App">
      <button onClick={handleClick}>Hello</button>

      {Array.from(Array(counter)).map((c, index) => {
        return <input key={c} type="text"></input>;
      })}
    </div>
  );
}

https://codesandbox.io/s/elastic-wave-36ous?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/s/elastic-wave-36ous?fontsize=14&hidenavigation=1&theme=dark

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM