简体   繁体   English

更改数组内部特定对象的属性的状态值

[英]Change the state value of the property of a particular object that is inside an array

Is there a way to mutate the value of done property of a particular item object in this.state.items when the user checks the checkbox of a targeted <li> ? 当用户选中目标<li>的复选框时,是否有办法在this.state.itemsthis.state.items特定项目对象的done属性值? For example, if I check the checkbox inside an <li> that has an ID of 0 , its done property will change into true . 例如,如果我选中ID为0<li>内的复选框,则其done属性将变为true

const Item = props => (
  <li>
    <input type="checkbox" checked={props.done} onChange={props.event} />
    <span>{props.name}</span>
  </li>
)


class Foo extends React.Component {
  state = {
    items: [
      { id: 0, name: 'Item 1', done: false },
      { id: 1, name: 'Item 2', done: false },
      { id: 2, name: 'Item 3', done: false }
    ]
  }

  toggleDone = (e) => {
    // ???
  }

  render() {
    return(
      <ul>
        {this.state.items.map(item => (

          <Item
            key={items.id}
            name={item.name}
            done={item.done}
            event={this.toggleDone} />

        ))}
      </ul>
    )
  }
}

First, you need to pass the index of the item to the event handler. 首先,您需要将项目的index传递给事件处理程序。

{this.state.items.map((item,index) => (
   <Item
      key={items.id}
      name={item.name}
      done={item.done}
      event={this.toggleDone.bind(this, index)} />
 ))}

Then, in your event handler, you can change the state like this 然后,在事件处理程序中,您可以像这样更改状态

toggleDone = (index, e) => {
    // Create new array and new object to avoid state mutation.
    let items = [...this.state.items];
    items[index] = Object.assign({}, items[index], {done: e.target.checked});

    // Set the state with the updated state.
    this.setState({ items });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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