2017-08-16 132 views
0

所以我的代码是:更新状态

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 
    }); 
} 
+0

你能提供'item'在'onPress'?例如:'{this.handleOnPress(item)}''或类似的? –

+0

@JeffHuijsmans你不能这样称呼它,或者handleOnPress将在每个物品的渲染上被调用。你需要按照我的回答做些事情:) –

+0

@MattDerrick很好,谢谢!我想在另一个框架的方式:) –

回答

3

你必须给它的参数,所以我们知道什么产品来增加:

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

或者这是一个有点更具可读性,但做同样的东西:

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

我有我的功能:'this.setState({thevalue:this.state.thevalue + 1});'但不工作。 – Somename

+0

@Somename什么是错误? –

+0

更新了我的问题。不知道我是否正确地做它 – Somename

1

你可以通过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> 
 
      } 
 
     /> 
 
    ) 
 
    } 
 
}

+0

我收到了'undefined不是一个对象(评估'data [idx] .thevalue')'我按照你的代码 – Somename

+0

'onPress = {(item)=> this.handleOnPress(item.id)}'你是否改变了' onPress'功能? –

+0

编号与此处完全相同。为idx提供相同的错误 – Somename