[英]React Calculator: How to prevent multiple decimals?
我幾乎已經完成了使用 React 構建一個簡單的計算器。 我只是有多個小數的問題。 我試圖做的是寫一個條件,但它不起作用。 請問你能幫幫我嗎?
這是我的代碼的一部分:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '0'
};
}
addToInput = e => {
const value = e.target.value;
const oldValue = this.state.input;
if (this.state.input != '0') {
this.setState({ input: (this.state.input + value) });
} else if (value == '.' && oldValue.includes('.')) {
console.log('Mulitple decimals');
} else {
this.setState({ input: value });
}
};
render() {
return (<Button addToInput={ this.addToInput } />);
}
}
class Button extends React.Component {
render() {
return (
<div className="row">
<button
value="."
id="decimal"
onClick={ this.props.addToInput }
>.
</button>
<button
value="0"
id="zero"
onClick={ this.props.addToInput }
>0
</button>
<button
value="-"
id="subtract"
onClick={ this.props.addToInput }
>-
</button>
</div>
);
}
}
先感謝您!
您可以查看傳入的值,檢查它是否為.
並檢查輸入是否已經有一個。 如果是,則什么也不做,否則將值添加到輸入的末尾:
addToInput = e => {
const { value } = e.target;
const { input } = this.state;
if (value === "." && input.includes(".")) {
return;
}
this.setState({ input: `${input}${value}` });
};
像這樣改變你addToInput
:
addToInput = e => {
const value = e.target.value;
const oldValue = this.state.input;
if (value === '.' && oldValue.includes('.')) {
console.log('Mulitple decimals');
return;
}
if (this.state.input !== '0') {
this.setState({ input: (this.state.input + value) });
} else {
this.setState({ input: value });
}
};
為什么你有問題:
addToInput = e => {
const value = e.target.value;
const oldValue = this.state.input;
if (this.state.input !== '0') {
// after first addToInput you will end up here ALWAYS
this.setState({ input: (this.state.input + value) });
} else if (value === '.' && oldValue.includes('.')) {
// You will never be here because this.state.input !== '0' is always true after first addToInput
console.log('Mulitple decimals');
} else {
// you will end up here only when you lunch your addToInput first time
this.setState({ input: value });
}
};
那么正則表達式會幫助你。
const regex = /^[1-9]\d*(\.\d+)?$/;
然后你可以檢查你的價值:
regex.test('222') // true
regex.test('222.') // false
regex.test('222.0') // true
regex.test('222.0.1') // false
regex.test('222.01234') // true
regex.test('abc') // false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.