我在做一个小费计算器。我有三个变量:提示、账单和人员。我想在输入输入值时显示计算值。当我尝试在账单输入中输入小数时,它不允许我输入小数。另外,当我单击人员输入时,它将从1开始。因此,如果我输入2,它将是12。如何解决此问题?
import "./styles.css";
import {useState} from 'react'
export default function App() {
const [calc, setCalc] = useState({
bill: 0,
tip: 0,
people: 1,
})
const [error, setError] = useState({
people: false,
bill: false
})
// var tipPerPerson = (calc.bill * (1 + (calc.tip/100)))/calc.people;
var tipPerPerson = (calc.bill * (calc.tip/100));
var totalPerPerson = (calc.bill + tipPerPerson)/calc.people;
const handleBillChange = (event) => {
const input = Number(event.target.value);
if (!isNaN(input)) {
setCalc({
...calc,
bill: input
});
}
};
const handleTipClick = (event) => {
const input = Number(event.target.value);
if (!isNaN(input)) {
setCalc({
...calc,
tip: input
});
}
};
const handlePeoplelChange = (event) => {
const input = Number(event.target.value);
if (!isNaN(input) && input > 0) {
setError({
...error,
people: false
});
setCalc({
...calc,
people: input
});
}
else {
setError({
...error,
people: true
});
}
};
const handleResetClick = () =>{
setCalc({
...calc,
bill: 0,
people: 1,
tip: 0
})
}
return (
<div className="App">
<div className="calculator">
<div className="calculator__item">
<label htmlFor="bill" >Bill: </label>
<input onChange={handleBillChange} placeholder="$0" value={calc.bill} id="bill" />
</div>
<div className="calculator__item tip__buttons">
<button value={10} onClick={handleTipClick}>10%</button>
<button value={15} onClick={handleTipClick}>15%</button>
<button value={20} onClick={handleTipClick}>20%</button>
</div>
<div className="calculator__item">
<label htmlFor="people">Number of People: </label>
<input onChange={handlePeoplelChange} placeholder="1" value={calc.people} id="people" />
{error.people && <p className="invalid">Can't be zero</p>}
</div>
</div>
<div className="display">
<p>
Tip Amount Per Person: {(tipPerPerson).toFixed(2)}
</p>
<p>Total Amount Per Person: {(totalPerPerson).toFixed(2)}</p>
<button onClick={handleResetClick}>Reset</button>
</div>
</div>
);
}
1条答案
按热度按时间scyqe7ek1#
将帐单输入更新为类型编号。
代码沙盒:https://codesandbox.io/s/eloquent-goldberg-yd6nvf?file=/src/App.js:442-579