簡體   English   中英

僅單擊元素的更新狀態

[英]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傳遞給函數? 如果是,我該怎么做?

非常感謝。

UPDATE1:

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)}

您可以通過idonPress然后更新相應的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> } /> ) } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM