this.state反应

时间:2019-02-10 15:16:45

标签: reactjs

我是学生,第一次是做这种项目,也是第一次使用React和这种语法。我遵循了一些教程,但现在停滞了。

当您单击所有数字时,应将它们加在一起。

我在哪里做错了?是我解析输入的地方吗?整个周末我都尝试过不同的方法,但是却无法解决。请帮助我进一步。

import React, { Component } from "react";
import './App.css';
import Button from './components/Buttons'; 
import Input from './components/Inputs';
import ClearButton from './components/ClearButtons';


class App extends Component {



  constructor(props) {
    super(props);

    this.state = {
      input: "",
      operator: ""
    };
  }


  addToInput = val => {
    this.setState({ input: this.state.input + val });
  }

  // If this.state.input is not empty then add zero
  // If this.state.input is not blank (another number has already been added in)
  addZeroToInput = val => {
    if (this.state.input !== "") {
      this.setState({ input: this.state.input + val });
    }
  };

  // Input = blank 
  clearInput = () => {
    this.setState({ input: "" });
  };

  add = () => {
    this.setState({ input: ""});
    this.state.operator = "plus";

    if (this.state.operator == "plus") {
      this.setState({
        input:
          parseInt(this.state.input) +
          parseInt(this.state.input)
      });
    }
  };

  mult = () => {
    this.setState({ input: "" });
    this.state.operator = "multiply";

    if (this.state.operator == "multiply") {
      this.setState({
        input:
          parseInt(this.state.input) *
          parseInt(this.state.input)
      });
    }
  };

  render() {

    return (
      <div className="App">
        <div className="wrapper">
          <div className="row">
            <Input>{this.state.input}</Input>
          </div>
          <div className="row">
            <Button handleClick={this.addToInput}>7</Button>
            <Button handleClick={this.addToInput}>8</Button>
            <Button handleClick={this.addToInput}>9</Button>
          </div>
          <div className="row">
            <Button handleClick={this.addToInput}>4</Button>
            <Button handleClick={this.addToInput}>5</Button>
            <Button handleClick={this.addToInput}>6</Button>
          </div>
          <div className="row">
            <Button handleClick={this.addToInput}>1</Button>
            <Button handleClick={this.addToInput}>2</Button>
            <Button handleClick={this.addToInput}>3</Button>
          </div>
          <div className="row">
            <Button handleClick={this.add}>+</Button>
            <Button handleClick={this.addZeroToInput}>0</Button>
            <Button handleClick={this.multiply}>*</Button>
          </div>
          <div className="row">
            <ClearButton handleClear={this.clearInput}>Clear</ClearButton>
          </div>
        </div>
      </div> 
    );
  }
}

export default App;

3 个答案:

答案 0 :(得分:0)

  

现在,当我单击4444 +时,它将显示8888,但它将显示16。

您的添加功能包括:

this.setState({
  input:
    parseInt(this.state.input) +
    parseInt(this.state.input)
});

在这种情况下,this.state.input将是"4444",您将其解析为整数并基本将其添加到自身,这就是为什么它是8888的原因。

如果您想要的输出是将每个数字彼此相加,如4+4+4+4,那么您需要按每个数字对this.state.input进行拆分,将其解析为整数,然后将其相加

> "4444".split("")
[ '4', '4', '4', '4' ]
> "4444".split("").map(Number)
[ 4, 4, 4, 4 ]
> "4444".split("").map(Number).reduce((x, y) => x + y)
16

不相关,但是您应遵循@Hemadri的建议来设置按钮的handleClick。或者,只需执行以下操作:

<button onClick={(e) => this.addToInput(e)}>1</button>

addToInput = event => {
  this.setState({input: this.state.input + event.target.innerText});
}

另外,不要直接改变状态,请使用setState()函数。

您也可以将其组合:

this.setState({input: ""});
this.state.operator = "plus";

对此:

this.setState({
  input: "",
  operator: "plus"
});

并摆脱if (this.state.operator == "plus"),因为您只需将运算符设置为plus,所以您无需检查它。

答案 1 :(得分:0)

在内部尝试这些代码
1.添加功能

    var values = 0;

    for (var i = 0; i < this.state.input.length; i++) {
        values += parseInt(this.state.input[i])
    }

    this.setState({
        input: values
    });

2。乘积函数

    var values = 0;

    for (var i = 0; i < this.state.input.length; i++) {
        values *= parseInt(this.state.input[i])
    }

    this.setState({
        input: values
    });

您将输入值当作一个字符串块。要解决,您必须从该字符串中获取每个值并像这样进行解析。

答案 2 :(得分:0)

因此,据我在代码中所看到的,您已经成功在输入中添加了数字(数字),但是在尝试解析输入数字以应用所选的运算符时遇到问题。

按下操作员时要执行的操作是: 1.将您的输入解析为个位数 2.将选定的运算符应用于解析的数字 3.输出结果(替换输入?)

  1. 可以用string.split
  2. 完成
  3. 可以用array.reduce
  4. 完成
  5. 是一个简单的setState
add = () => {
  const { input } = this.state
  const digits = input.split('')
  const output = digits.reduce((sum, digit) => sum + parseInt(digit, 10), 0)
  this.setState({ input: output })
  // or if you want to preserve the input, add an output key to the state and
  // this.setState({ output })
}

multiply = () => {
  const { input } = this.state
  const digits = input.split('')
  const output = digits.reduce((product, digit) => product * parseInt(digit, 10), 1)
  this.setState({ input: output })
  // or if you want to preserve the input, add an output key to the state and
  // this.setState({ output })
}

请注意,这将您限制为一位数操作。添加空格键来分隔数字要容易得多,然后使用input.split(' ')将输入转换为数字,该数字会将所有数字(甚至多个数字)整齐地存储到数组中。

相关问题