简体   繁体   中英

how to make an appending input and send value to an array and Axios.post it

I want to know how to make a button that makes a new <input> everytime user clicks it and I want its value to be added to an array and post it with Axios.

(I used this piece of code for the most of my pages and works fine, but if I need to change it for posting arrays please tell me)

    function roundTable() {
      const config = {
        headers: {
          "x-auth-token": sessionStorage.getItem('token'),
          "Accept": "application/json",
          "Content-Type": "application/json",
        }
      };
    
      const bodyParameters = { ... };
    
      const handleAdd = () => {
  const handleAdd = () => {
    setLoading(true);
    axios.post('localhost', bodyParameters, config).then(response => {
      setLoading(false);
      console.log(response)        })
      }

mostly I want to know how can I put a group of input values, to an array React is really new to me, id be very happy if someone could help me with this!

I want to know how to make a button that makes a new every time user clicks it and I want its value to be added to an array and post it with Axios.

It feels there are two questions in one here; first is how to deal with the state (amount of inputs) and second how to save the array.

I can't really help with the second one without examining how setLoading exactly works, but I have a suggestion for dealing with the state. Add each input value as a string into an array and do something like this:

 document.onreadystatechange = () => { const { useState } = React; function Boxes() { const [inputs, setInputs] = useState([]); const addInput = () => { setInputs(inputs.concat("abc")); }; const changeInput = (index, value) => { const updated = [...inputs]; updated[index] = value; setInputs(updated); }; const handleAdd = () => { alert("Saving " + JSON.stringify(inputs)); }; return ( <div> <p>inputs</p> {inputs.map((input, index) => { return ( <div key={index}><input type="text" value={input} onChange={(e) => changeInput(index, e.target.value)} /></div> ); })} <button onClick={addInput}>Add new input</button> <hr /> <button onClick={handleAdd}>Add</button> </div> ); } ReactDOM.render(<Boxes />, document.querySelector("#root")); };
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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