仅更新单击元素的状态

时间:2017-08-16 15:02:02

标签: javascript reactjs react-native

所以我的代码是:

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

2 个答案:

答案 0 :(得分:3)

你必须给它一个参数,以便我们知道要增加的项目:

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

或者这有点可读但做同样的事情:

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

答案 1 :(得分:1)

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

&#13;
&#13;
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>
            }
        />
    )
  }
}
&#13;
&#13;
&#13;