Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - React Multiple Input value in single array

Hi I am making a react component which roughly looks like this below

import React, { useState } from "react";

export default function App() {
  const [data, setData] = useState([
    {
      id: 1,
      value: []
    },
    {
      id: 1,
      value: []
    }
  ]);

  const onchangeInput = (val, index) =>{
    let temp = ['',''];
    temp[index] = val.target.value
    console.log(temp)
  }

  return (
    <>
      {data.map((value, index) => {
        return <input key={index} onChange={(val)=>{onchangeInput(val, index)}} /> 
      })}
    </>
  );
}

In function onchangeInput I created an array variable temp where I want to store both input values , for example in first input if I insert first and in second value if I insert second then I want to have the temp value to ['first','second'] but everytime if I insert one input item , the other input item is resetting. How can I store both value in my temp array ?

Here is a live link of this code

question from:https://stackoverflow.com/questions/65943137/react-multiple-input-value-in-single-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not using data and setData that you define in start of the component. Change it like this:

const onchangeInput = (val, index) => {
    let temp = data;
    temp[index] = val.target.value;
    setData(temp);
    console.log(temp);
  };

What I did is temp contains now data which is empty on first time. setData will save temp contents.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...