点击(react.js)

时间:2019-05-11 19:47:27

标签: reactjs

我对“应用”中的数字输入总和有一些疑问。我不知道我怎么能得到这笔款项。我有一些数字输入。 它们的数量可能不同。用户必须在每个数字字段中输入一些金额。 点击“计算”按钮后,此数字输入的总和应显示在p> span中。 这里的代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">
class Sum extends React.Component {
  constructor() {
    super();
    this.state = {
      elements: ["main work", "freelance"],
      value: "",
      numberValue: ""
    };
    this.adder = this.adder.bind(this);
    this.reset = this.reset.bind(this);
    this.handleChange = this.handleChange.bind(this);
    // this.handleChangeNumber = this.handleChangeNumber.bind(this);
  }
  adder() {
    this.state.elements.push(this.state.value);
    this.setState({
      elemements: this.state.elements
    });
  }
  reset() {
    this.setState({
      elements: this.state.elements.slice(1, 1)
    });
  }
  handleChange(e) {
    this.setState({
      value: e.target.value
    });
  }
  // handleChangeNumber(e) {
  //   this.setState({
  //     numberValue: e.target.value
  //   });
  // }
  delCurrent(index) {
    this.state.elements.splice(index, 1);
    this.setState({
      elements: this.state.elements
    });
  }
  render() {
    const list = this.state.elements.map((element, index) => {
      return (
        <li key={index}>
          {element}:{" "}
          <input
            style={{ width: 70, marginBottom: 2 }}
            type="number"
            value={this.state.numberValue}
            // onChange={this.handleChangeNumber}
          />
          <span>USD</span>
          <button
            style={{ cursor: "pointer" }}
            onClick={this.delCurrent.bind(this)}
          >
            &times;
          </button>
        </li>
      );
    });
    return (
      <div>
        <h3>Cash control 'app'</h3>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
          placeholder="your income"
        />
        <button style={{ cursor: "pointer" }} onClick={this.adder}>
          add to list
        </button>
        <button style={{ cursor: "pointer" }} onClick={this.reset}>
          reset
        </button>
        <ol>{list}</ol>
        <p>
          Total sum: <span />
        </p>
        <button style={{ cursor: "pointer" }}>calculate</button>
      </div>
    );
  }
}
ReactDOM.render(<Sum />, document.getElementById("root"));
</script>

我希望你们能帮助我,ty

2 个答案:

答案 0 :(得分:2)

将元素更改为对象,每个对象都有自己的数量。

elements: [
    { title: 'main work', amount: 0 },
    { title: 'freelance', amount: 0 }
  ]

在您的加法器中,请勿将项目推入状态,例如this.state.elements.push(this.state.value);

adder() {
  this.setState({
    elements: [...this.state.elements, { title: this.state.value, amount: 0 }]
  });
}

要计算总数,请遍历项目并求和

calculate = () => {
  let totalAmount = 0;
  this.state.elements.forEach(item => {
    totalAmount += item.amount;
  });

  this.setState({
    totalAmount
  })
}

处理输入更改

handleChangeNumber(e, index, title) {

  const amount = parseInt(e.target.value, 10);
  const element = { title, amount };

  this.setState({
    elements: [
      ...this.state.elements.slice(0, index),
      Object.assign({}, this.state.elements[index], element),
      ...this.state.elements.slice(index + 1)
    ]
  });
}

传递元素的索引和标题以处理.map中的输入函数

const list = this.state.elements.map((element, index) => {
  return (
    <li key={index}>
      {element.title}:{" "}
      <input
        style={{ width: 70, marginBottom: 2 }}
        type="number"
        value={this.state.elements[index].amount}
        onChange={(e) => this.handleChangeNumber(e, index, element.title)}
      />
      <span>USD</span>
      <button
        style={{ cursor: "pointer" }}
        onClick={() => this.delCurrent(index)}
      >
        &times;
      </button>
    </li>
  );
});

计算并显示总和

<p>
  Total sum: <span>{`$ ${this.state.totalAmount}`}</span>
</p>
<button onClick={this.calculate} style={{ cursor: "pointer" }}>calculate</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">
class Sum extends React.Component {
  constructor() {
    super();
    this.state = {
      elements: [{ title: "main work", amount: 0 }, { title: "freelance", amount: 0 }],
      value: "",
      numberValue: "",
      totalAmount: 0,
    };
    this.adder = this.adder.bind(this);
    this.reset = this.reset.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleChangeNumber = this.handleChangeNumber.bind(this);
  }
  adder() {
    this.setState({
      elements: [...this.state.elements, { title: this.state.value, amount: 0 }],
      value: '',
    });
  }
  reset() {
    this.setState({
      elements: this.state.elements.slice(1, 1),
      totalAmount: 0,
      value: '',
    });
  }
  handleChange(e) {
    this.setState({
      value: e.target.value
    });
  }

  calculate = () => {
    let totalAmount = 0;
    this.state.elements.forEach(item => {
      totalAmount += item.amount;
    });

    this.setState({
      totalAmount
    })
  }

  handleChangeNumber(e, index, title) {
    
    const amount = parseInt(e.target.value, 10);
    const element = { title, amount };

    this.setState({
      elements: [
        ...this.state.elements.slice(0, index),
        Object.assign({}, this.state.elements[index], element),
        ...this.state.elements.slice(index + 1)
      ]
    });
  }

  delCurrent(index) {
    this.state.elements.splice(index, 1);
    this.setState({
      elements: this.state.elements
    }, this.calculate);
  }
  render() {
    const list = this.state.elements.map((element, index) => {
      return (
        <li key={index}>
          {element.title}:{" "}
          <input
            style={{ width: 70, marginBottom: 2 }}
            type="number"
            value={this.state.elements[index].amount}
            onChange={(e) => this.handleChangeNumber(e, index, element.title)}
          />
          <span>USD</span>
          <button
            style={{ cursor: "pointer" }}
            onClick={() => this.delCurrent(index)}
          >
            &times;
          </button>
        </li>
      );
    });
    return (
      <div>
        <h3>Cash control 'app'</h3>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
          placeholder="your income"
        />
        <button style={{ cursor: "pointer" }} onClick={this.adder}>
          add to list
        </button>
        <button style={{ cursor: "pointer" }} onClick={this.reset}>
          reset
        </button>
        <ol>{list}</ol>
        <p>
          Total sum: <span>{`$ ${this.state.totalAmount}`}</span>
        </p>
        <button onClick={this.calculate} style={{ cursor: "pointer" }}>calculate</button>
      </div>
    );
  }
}
ReactDOM.render(<Sum />, document.getElementById("root"));
</script>

答案 1 :(得分:0)

获取数字输入总和的更好方法是为每个数字输入组成一个小的组件,并保持数字输入组件内部的状态。单击“计算”按钮后,您可以使用状态提升概念react来获取每个组件的状态(数值),并且可以计算总和。

希望它能回答您的问题。