react-native - 如果我在我的任何按钮上使用 onPress,它们都会改变状态。我想要独立的国家
问题描述
如果我在我的任何按钮上使用 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>
解决方案
你可以做这样的事情
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>
推荐阅读
- python - 制作动画包 - 好的做法?
- c# - 使用 ProcessStartInfo 从现有 C# 应用程序调用 C# 应用程序?
- r - Shiny App R如何仅在退出而不是会话结束时执行代码?
- ruby-on-rails - 尽管在 Rails 6 应用程序中将它们列入白名单,但 ActionText 仍去除 iframe 标记
- java - Spring aop 方面未触发
- python - 有没有一种简单的方法可以在数据框中隔离 YYYY-MM-DD 格式的给定日期间隔?
- xml - 需要一个 XSD 结构来解析 DiffGram 数据
- java - 如何使用 DocuSign 生成的公钥和私钥生成 .jks 文件
- c# - 如何使用我覆盖的比较方法?
- javascript - jQuery 填充字段返回 Vee 验证错误