0

如果我在我的任何按钮上使用 onPress,它们都会改变状态,它们会显示相同的值。我希望它们使用相同的 2 个函数(增量和减量)彼此独立。

this.state = {
   packs: 0
};

incrementPacks = () => {
    this.setState({
      packs: this.state.packs + 1
    })
  }

  decrementPacks = () => {
    this.setState({
      packs: this.state.packs - 1
    })
  }

<View style={styles.iceBtnContainer}>
    <Button title='-' onPress={this.decrementPacks} />
    <Text style={styles.count}>{this.state.packs}</Text>
    <Button title='+' onPress={this.incrementPacks} />
</View>


<View style={styles.bufPadBtnContainer}>
    <Button title='-' onPress={this.decrementPacks} />
    <Text style={styles.count}>{this.state.packs}</Text>
    <Button title='+' onPress={this.incrementPacks} />
</View>
4

1 回答 1

0

你可以做这样的事情

this.state = {
   icePacks: 0,
   bufPadPacks: 0
};

incrementPacks = type => {
   if(type === "Ice") {
    this.setState({ icePacks: this.state.icePacks + 1 })
   } else if(type === "BufPad") {
    this.setState({ bufPadPacks: this.state.bufPadPacks + 1 })
  }

  }

  decrementPacks = type => {
   if(type === "Ice") {
    this.setState({ icePacks: this.state.icePacks - 1 })
   } else if(type === "BufPad") {
    this.setState({ bufPadPacks: this.state.bufPadPacks - 1 })
  }

  }

<View style={styles.iceBtnContainer}>
    <Button title='-' onPress={() => this.decrementPacks("Ice")} />
    <Text style={styles.count}>{this.state.icePacks}</Text>
    <Button title='+' onPress={() => this.incrementPacks("Ice")} />
</View>


<View style={styles.bufPadBtnContainer}>
    <Button title='-' onPress={() => this.decrementPacks("BufPad")} />
    <Text style={styles.count}>{this.state.bufPadPacks}</Text>
    <Button title='+' onPress={() => this.incrementPacks("BufPad")} />
</View>
于 2019-06-05T14:54:31.570 回答