首页 > 解决方案 > 限制输入数量

问题描述

我正在尝试制作一个 React 计算器。大部分都完成了,但我有一个问题我不知道如何纠正:我不想让用户输入以多个“0”开头的表达式,并且应该将“01”等表达式替换为“1”。我想过使用字符串方法来限制它,但它并没有让步。编辑:我知道为什么我的解决方案不起作用(输入永远不会超过一个零),但我不知道有任何其他方法可以解决它。

class Calculator extends Component {
constructor(props) {
    super(props);
    this.state = { value: "" };
    this.handleClick = this.handleClick.bind(this);
}
handleClick(evt) {
    const id = evt.target.id;
    const result = evt.target.value;
    if (id === "clear") {
    this.setState({ value: 0 });
    } else if (id === "equals") {
    this.setState({ value: math.eval(this.state.value) });
    } else {
    result.toString().includes("00");
    this.setState({ value: this.state.value + result.replace("00", "0") });
    console.log(this.state.value);
    }
}

render() {
    return (
    <div id="container">
        <Display value={this.state.value} />
        <Button onClick={this.handleClick} id="zero" value={"0"} />
        <Button onClick={this.handleClick} id="one" value={"1"} />
        <Button onClick={this.handleClick} id="two" value={"2"} />
        <Button onClick={this.handleClick} id="three" value={"3"} />
        <Button onClick={this.handleClick} id="four" value={"4"} />
        <Button onClick={this.handleClick} id="five" value={"5"} />
        <Button onClick={this.handleClick} id="six" value={"6"} />
        <Button onClick={this.handleClick} id="seven" value={"7"} />
        <Button onClick={this.handleClick} id="eight" value={"8"} />
        <Button onClick={this.handleClick} id="nine" value={"9"} />
        <Button onClick={this.handleClick} id="decimal" value={"."} />
        <Button onClick={this.handleClick} id="equals" value={"="} />
        <Button onClick={this.handleClick} id="clear" value={"clear"} />
        <Button onClick={this.handleClick} id="add" value={"+"} />
        <Button onClick={this.handleClick} id="subtract" value={"-"} />
        <Button onClick={this.handleClick} id="multiply" value={"*"} />
        <Button onClick={this.handleClick} id="divide" value={"/"} />
    </div>
    );
}
}
export default Calculator;

标签: reactjs

解决方案


A few pointers...

  • If you want value to be a string, make sure you don't change it to a number anywhere. You're doing this when id === 'clear'
  • If you only want to test for "00" at the beginning of value, use startsWith, not includes.
  • If you are using setState and the new state depends on the previous state, you must first access the state's previous value. The rationale for this is in the docs.

@daniel-hilgarth provides the correct way to use setState in this case.

Remove leading zero:

this.setState(prevState => ({
  value: `${prevState.value}${result}`.replace(/^0+\B/, "")
}));

There's all sorts of ways to do this. The regex above will identify leading zeros. For the case where you have only "0", it doesn't match at all because "0" followed by a end of string (or boundary) doesn't match the regex which is "0" followed by "not a word boundary".


推荐阅读