仅更新被点击元素的状态

Update state of only the clicked element

所以我的代码是:

export default class MyClass extends Component {

  constructor(props) {
    super(props);
    this.state = {
        data: [
          {id: 101, name:"One", thevalue:11},
          {id: 102, name:"Two", thevalue:22},
          {id: 103, name:"three", thevalue:33}
        ]
    }
  }

  handleOnPress() {
    << HOW DO I CODE THIS ?? >>
    I want to increase the number count in thevalue of the pressed item
  }

  render() {
      return(
        <FlatList
            data = {this.state.data}
            renderItem = {
                ({item}) => 
                <TouchableOpacity onPress={this.handleOnPress} >
                    <Text> {item.name} + {item.thevalue} </Text>
                </TouchableOpacity>
            }
        />
    )
  }
}

我希望能够仅增加单击项目的 thevalue 的计数。所以我应该做一个 setState 对吧?但是我怎么知道我需要为哪个项目 运行 呢?我是否需要将点击项目的 id 传递给函数?如果是,我该怎么做?

非常感谢。

更新1:

handleOnPress(id) {
      this.setState({
        thevalue: this.state.thevalue+1
    });
}

你必须给它一个参数,这样我们才能知道要递增的项目:

onPress={this.handleOnPress.bind(this, item.id)}
...
handleOnPress(id) {
    // increment id
}

或者这更具可读性但做同样的事情:

onPress={() => this.handleOnPress(item.id)}

你可以将id传递给onPress然后更新相应的thevalue

export default class MyClass extends Component {

  constructor(props) {
    super(props);
    this.state = {
        data: [
          {id: 101, name:"One", thevalue:11},
          {id: 102, name:"Two", thevalue:22},
          {id: 103, name:"three", thevalue:33}
        ]
    }
  }

  handleOnPress(id) {
    let {data} = this.state;
    let idx = data.findIndex(x => x.id == id);
    data[idx].thevalue ++;
    this.setState({data});
  }

  render() {
      return(
        <FlatList
            data = {this.state.data}
            renderItem = {
                ({item}) => 
                <TouchableOpacity onPress={() => this.handleOnPress(item.id)} >
                    <Text> {item.name} + {item.thevalue} </Text>
                </TouchableOpacity>
            }
        />
    )
  }
}