编辑
能够让它工作,但现在当我点击“税收”按钮时,它说结果是 NaN。我该如何解决?
用 react-native 构建一个小型计算应用程序。除了税收按钮外,所有按钮都有效。对于 Tax 按钮,我需要它在两个数字的加法、减法、乘法或除法的结果中加上 12%。有人可以帮助我了解我在这里做错了什么吗?尝试在线查找,但无法找到解决方案。如果有人指出错误,我们将非常高兴。
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
export default class Counter extends React.Component {
state = {
num: 0,
}
inp1 = 0;
inp2 = 0;
handleSubtract = () => {
this.setState({
num:this.inp1-this.inp2
})
}
handleAdd = () => {
this.setState({
num: this.inp1 + this.inp2
})
}
handleDivide = () => {
this.setState({
num: this.inp1 / this.inp2
})
}
handleMultiply = () => {
this.setState({
num: this.inp1 * this.inp2
})
}
handleTax = () => {
var newNum = this.num / 100 * 12;
this.setState({
num: newNum
})
}
handleNum1 = (text) => {
this.inp1 = parseInt(text);
}
handleNum2 = (text) => {
this.inp2 = parseInt(text);
}
render() {
return (
<View style={styles.flexBox}>
<Text style={styles.flexTitle}>Hi, welcome to my app!</Text>
<View style={styles.inpBox}>
<TextInput
style={[styles.inps, {marginRight: 10}]}
placeholder="Num1"
keyboardType="phone-pad"
onChangeText={this.handleNum1}
/>
<TextInput
style={styles.inps}
placeholder="Num2"
keyboardType="phone-pad"
onChangeText={this.handleNum2}
/>
</View>
<View style={styles.butBox}>
<View style={styles.button}>
<Button
onPress={this.handleSubtract}
title="Subtract"
/>
</View>
<View style={styles.button}>
<Button
onPress={this.handleAdd}
title="Add"
/>
</View>
<View style={styles.button}>
<Button
onPress={this.handleMultiply}
title="Multiply"
/>
</View>
<View style={styles.button}>
<Button
onPress={this.handleDivide}
title="Divide"
/>
</View>
<View style={[styles.button, {height: 65, width: 65}]}>
<Button
onPress={this.handleTax}
title="Tax"
color="#f00"
/>
</View>
</View>
<Text style={styles.numBox}>
{this.state.num}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
flexBox: {
flex: 1,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
},
flexTitle: {
padding: 10,
},
inpBox: {
flexDirection: "row",
},
inps: {
width: "20%",
height: 50,
textAlign: "center",
},
butBox: {
flexDirection: "row",
width: "100%",
alignItems: "center",
},
button: {
width: "20%",
height: 50,
},
numBox: {
padding: 20,
fontSize: 32,
}
});
最佳答案
您的代码中只有一个错误可以使其按您希望的方式工作。
在你的函数中 handleTax
您指的是错误的 num
。
而不是 this.num
像这样引用它 - this.state.num
将如下所示:
handleTax = () => {
var newNum = this.state.num / 100 * 12;
this.setState({
num: newNum
});
}
这将消除 NaN 结果。
要进行正确的税收计算,如下所示:
var newNum = this.state.num + this.state.num * 0.12;
关于reactjs - 如何使百分比按钮在 react-native 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52324583/