简体   繁体   中英

Getting a value of inputs populated Dynamically React.js

I am pretty new to React, I have worked on react native before, so I am quite familiar with a framework. Basically I have an array of objects, lets say in contains 5 items. I populated views based on the amount of objects, so if there are 5 objects, my map function would populate 5 together with 5 inputs. My question is how can I get a value of each input? Here is my code:

array.map(map((item, index) => (
    <h1> item.title </h1>
    <input value={input from user} />
)

You have to use the state and update the value with onChange manually

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: ''
    }
  }
  handleInputChange(e) {
    this.setState({
        [e.target.name]: e.target.value
    });
  }
  render () {
    return (
      <div>
        <input value={this.state.value} onChange={(e) => {this.handleInputChange(e)}} />

      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

A quick solution would be to use an array for all the input values.

const Inputs = ({array}) => {
    const [inputs, setInputs] = useState([]);

    const setInputAtIndex = (value, index) => {
        const nextInputs = [...inputs]; // this can be expensive

        nextInputs.splice(index, 1, value);

        setInputs(nextInputs);
    }

    return (
        ...
        array.map((item, index) => (
            <div key={index}>
                <h1>{item.title}</h1>
                <input
                    value={inputs[index]}
                    onChange={({target: {value}) => setInputAtIndex(value, index)}
                />
            </div>
        )
        ...
    );
}

Keep in mind here that in this case every time an input is changed, the inputs state array is copied with [...inputs] . This is a performance issue if your array contains a lot of items.

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