我几乎已经使用 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 });
}
};
关于javascript - react 计算器 : How to prevent multiple decimals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399297/