我已经为支付费用写了这个计算器。现在,我需要检查输入的内容是否为空+是一个数字,否则将引发错误消息,指出“该字段不能为空”。我开始添加它,但在此过程中感到困惑。在此示例中,处理错误处理的最佳/最干净方法是什么?也许我应该将错误处理工作放到一个单独的组件中?
import React, { Component } from "react";
import styles from "./../styles.module.less";
class Calc extends Component {
constructor(props) {
super(props);
this.state = {
popoverOpen: false,
cost: 0,
homePrice: 0,
downPaymentAmt: 0,
downPaymentPrc: 0,
termOfLoan: 0,
annualInterestRate: 0,
formError: '',
inputValid: false
};
}
handleStateChange = e => {
const {
target: { name, value },
} = e;
this.setState({ [name]: value });
};
handleCostChange = () => {
const {
homePrice,
downPaymentAmt,
termOfLoan,
annualInterestRate,
} = this.state;
const principal = homePrice - downPaymentAmt;
const lengthOfLoan = 12 * termOfLoan;
const percentageRate = annualInterestRate / 1200;
// Formula M = P[i(1+i)^n]/[(1+i)^n -1]
const cost =
(principal * percentageRate) /
(1 - Math.pow(1 + percentageRate, lengthOfLoan * -1)).toString();
this.setState({
cost: cost.toFixed(2),
});
};
render() {
return (
<div>
<div className={styles.row}>
<div className={styles.col12}>
<h1 className={styles.calch1}>
Your home-buying by numbers
</h1>
<div
className={`${styles.positionRelative} ${
styles.formGroup
}`}>
<label htmlFor="name" >
Home price
</label>
<label s" formError={this.state.formError}>The field can't be empty</label>
<div className={styles.inputGroup}>
<div className={styles.inputGroupPrepend}>
<span className={styles.inputGroupText}>
$
</span>
</div>
<input
type="text"
id="input3-group1"
className={styles.formControl}
name="homePrice"
value={this.state.value}
onChange={this.handleStateChange}
placeholder="Amount of home's selling price"
/>
</div>
</div>
</div>
</div>
<div className={styles.row}>
<div className={styles.col12}>
<div
className={`${styles.positionRelative} ${
styles.formGroup
}`}>
<label htmlFor="name" className="">
Loan program
</label>
<div className={styles.inputGroup}>
<input
type="text"
id="name"
required=""
className={styles.formControl}
name="termOfLoan"
value={this.state.value}
onChange={this.handleStateChange}
placeholder="Original number of years to pay off your mortgage"
/>
</div>
</div>
</div>
</div>
<div className={`${styles.col6} ${styles.colsm4}`}>
<div
className={`${styles.positionRelative} ${
styles.formGroup
}`}>
<label
htmlFor="name"
className=""
style={{ display: "block" }}>
</label>
<button
className={`${styles.btn} ${
styles.btnWarning
} ${styles.btnSm}`}
style={{
fonSize: 16,
height: "35px",
color: "white",
}}
onClick={this.handleCostChange}>
Calculate!
</button>
</div>
</div>
</div>
<div className={styles.row}>
<div className={styles.col}>
<h2 className={styles.calch2}>
Your monthly mortgage
</h2>
<div className={styles.tableResponsive}>
<table
className={`${styles.borderLess} ${
styles.table
}`}>
{/* <thead>
<tr>
<th>Estimated monthly</th>
<th>taxes</th>
<th>Insurance</th>
<th>P&I</th>
</tr>
</thead> */}
<tbody>
<tr className={styles.output}>
<td>
${this.state.cost.toLocaleString()}
</td>
<td className={styles.tdlabel}>
PER MONTH
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
}
export default Calc;
答案 0 :(得分:0)
您可以收听onBlur
事件。当用户离开输入字段时发生。因此,在您的输入字段中添加onBlur
事件监听器。
例如:对于房屋价格
<input
type="text"
id="input3-group1"
className={styles.formControl}
name="homePrice"
// assign value as this.state.homePrice
value={this.state.homePrice}
// Add onBlur and use handleValidation event handler
onBlur={this.handleValidation}
onChange={this.handleStateChange}
placeholder="Amount of home's selling price"
/>
// for testing add this line just below the input field
// it will display form error
{ this.state.formError && <span>{this.state.formError} </span> }
现在将handleValidation
方法添加到您的组件
handleValidation = (e) => {
let { value } = e.target
// check if value is empty or not
if (value.trim().length === 0) {
this.setState({formError: 'Input field is required'})
return
// check if value is number or not
} else if (isNaN(Number(value))) {
this.setState({formError: 'Input field value must be a number'})
return
} else {
this.setState({ formError: ''})
}
}
更新
handleCostChange = (e) => {
// for testing only not needed
let { value } = e.target;
// Checking whether "e.target.value" on button is empty or not
console.log('some',value,'text') // some text
console.log(value.trim().length === 0) // true
const {
homePrice,
downPaymentAmt,
termOfLoan,
annualInterestRate,
} = this.state;
// updates
if (homePrice.trim().length === 0) {
this.setState({formError: 'Input Fields are required'})
return
} else if (isNaN(Number(homePrice))) {
this.setState({formError: 'Input Fields must be number'})
return
}
const principal = homePrice - downPaymentAmt;
const lengthOfLoan = 12 * termOfLoan;
const percentageRate = annualInterestRate / 1200;
// Formula M = P[i(1+i)^n]/[(1+i)^n -1]
const cost =
(principal * percentageRate) /
(1 - Math.pow(1 + percentageRate, lengthOfLoan * -1)).toString();
this.setState({
cost: cost.toFixed(2),
// update
formError: ''
});
};
还要更改
this.state = {homePrice: 0}
到
this.state = {homePrice: ''}
这是必需的,因为我使用了trim()
方法,它是一个字符串方法。因此,当您提交而未触摸输入字段时,将会收到错误消息。