我正在使用React JS开发一个简单的计算器应用程序。大多数事情都按预期工作。但是,我希望操作符参数在连续点击两个或多个包含操作符号的按钮时发生变化,例如,“*”,“+”。
下面是代码的相关部分以供参考
class Calculator extends React.Component {
constructor(props) {
super(props);
this.state = {
previous: "",
current: "",
operation: "",
};
}
clear = () => {
this.setState(() => ({
previous: "",
current: "0",
operation: null,
}));
};
delete = () => {
this.setState(() => ({
current: this.state.current.slice(0, -1),
}));
};
appendNumber = (number) => {
const { current } = this.state;
{ current === "0" && this.delete() }
if (number === "." && current.includes(".")) return;
this.setState((prevState) => ({
current: prevState.current + number,
}));
};
chooseOperation = (op) => {
const { previous, current, operation } = this.state;
if (current === "") return;
if (previous !== "") {
this.compute();
}
this.setState((prevState) => ({
operation: op,
previous: prevState.current,
current: "",
}));
};
compute = () => {
let computation;
const { previous, current, operation } = this.state;
const prev = parseFloat(previous);
const curr = parseFloat(current);
if (isNaN(previous) || isNaN(current) || !operation) return;
switch (operation) {
case "+":
computation = prev + curr;
break;
case "-":
computation = prev - curr;
break;
case "*":
computation = prev * curr;
break;
case "÷":
computation = prev / curr;
break;
default:
return;
}
this.setState({
current: computation,
operation: "",
previous: "",
});
if (operation != null) {
this.setState({
previous: `${previous} ${operation} ${current}`,
});
}
}
字符串
以下是我尝试的几件事:在ExciseOperation方法中,我尝试使用条件更新操作符参数来实现上述功能
if (["÷", "*", "+", "-"].some((value) => operation.includes(value))) {
this.setState((prevState) => ({
operation: prevState.operation.replace(/[\+\-\*\/]/g, op),
}));
} else {
this.setState({
operation: op,
});
}
型
我也试过这个
const lastChar = operation.charAt(operation.length - 1);
if (["÷", "*", "+", "-"].includes(lastChar)) {
this.setState({
operation: operation.slice(0, -1) + op,
});
} else {
this.setState((prevState) => ({
operation: `${prevState.operation} ${op}`,
previous: prevState.current,
current: "",
}));
}
型
为了解决这个问题,我在compute方法中的switch语句之前写了一个条件语句
if (["÷", "*", "+", "-"].some((value) => operation.includes(value))) {
this.setState((prevState) => ({
operation: prevState.operation.slice(0, -1),
}));
}
型
然而,到目前为止,这些功能都没有工作。我既没有尝试,也不想添加任何额外的参数,因为大多数其他功能都可以安静地工作。
2条答案
按热度按时间bihw5rsg1#
当用户输入一个数字(6),然后输入一个操作符(+),一切都很好。在state中,我们现在有
{previous: 6, operation: "+", current: ""}
。但是当用户按下另一个操作符时,if (current === "") return;
行开始工作,没有更新发生。为了解决这个问题,我们将始终允许更新运算符,您运行compute的条件在哪里是有意义的,然后在适当的时候更新
previous
和current
属性。字符串
hmmo2u0o2#
我有点明白了,下面提到的那个版本似乎可以做到这一点。
字符串
我修改了包含这个.compute()的条件。