Use of array.map and onchange in React

陌路散爱 提交于 2021-02-08 07:43:29

问题


The code below contains an array.map function what is the function of term and i and where was it gotten from, and what does the array.map and the onchange do

import React, { Component } from 'react';

class Apps extends Component {

componentDidMount() {
}

iLikeFunctions() {
console.log('yay functions');
}

render() {

var array = ['here','we','go'];

var no = 'yes';
const display = 'My Name';

return (
  <div>
    <p>{display}</p>
    <hr />
    <input type="text" onChange={this.iLikeFunctions} />
    <table>
      <tbody>
        {array.map((term,i) => {
          no = 'no';
          return (
            <tr key={i}>
              <td>{term}</td>
              <td>{no}</td>
            </tr>
          )
        })}
      </tbody>
    </table>
  </div>
 );

  }
}

export default Apps;

回答1:


Map:

The map() method creates a new array with the results of calling a provided function on every element in the calling array. So in the following line:

array.map((term,i)

You are mapping the array called array and looping through the array, assigning the word term for each value in the array and return a tr element for each array element with their respective value, index and variable string printed on the <tr>.

Key:

i is the index of the respective value which acts as a key since you didn't specify unique key ids for the elements.

A "key" is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.

Do note that it is not recommended to use indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

Check out the keys section in the official React Docs for a more in-depth explanation of keys.

onchange:

onchange watches the input field for any change and when it detects a change, it runs the iLikeFunctions().


tldr: The above code loops through array ['here','we','go']; and returns a <tr> for each value. It also runs the iLikeFunctions() whenever the input field value is changed.



来源:https://stackoverflow.com/questions/50945554/use-of-array-map-and-onchange-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!