我几乎已经使用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
:
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 });
}
};