引用数组中的对象

时间:2018-07-22 15:34:25

标签: javascript reactjs

请我如何引用(更改或删除)对象数组中的特定对象,例如

var myArray = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ]


//initial state for number set as an array
state = {
  number: []
}

//a function which runs any time a button called create is clicked
increment = () => {
  this.setState({
    numbers: [...this.state.number, {
      id: Date.now()
    }],
  })
}
//the array looks like this: number=[{id:53432},{id:34534},{id:434553}]

//the array is passed on to a component using the map function
{
  this.state.numbers.map(number => < Section key = {
        number.id
      }
      />)}

Section组件中,我有一个与数组的每个字段关联的按钮。 单击按钮时如何引用特定对象?例如,一个函数,用于记录数组中按下按钮的对象的ID

1 个答案:

答案 0 :(得分:0)

var myArray = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ]
handleClick(id){
    console.log('clicked id is', id);
}
myArray.map((item) => {
    <Button onClick={ () => this.handleClick(item.id)} />
})