计算反应中的数量和总价 [英] Calculating quantity and price total in react

查看:36
本文介绍了计算反应中的数量和总价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的一个非常新的用户,我在尝试设计一个应用时遇到了问题.基本上我想要一个产品列表,我可以让用户更新数量,每个数量的总数将出现在产品下方,整个包裹的总数将出现在底部.如果有人能帮我解决这个问题,我将不胜感激.我的代码包含在下面`

import React, { Component } from "react";从./logo.svg"导入标志;导入./App.css";类 App 扩展组件 {使成为() {/* 这是App的Counter部分,用来表示物品的数量*/类计数器扩展了 React.Component {构造函数(道具){超级(道具);this.state = {计数:0};}onUpdate = (val) =>{this.setState({计数:val});};使成为() {返回 (<div><CounterChild onUpdate={this.onUpdate}/><br/><OtherChildpassedVal={this.state.count}/>

)}}/*计数器部分到此结束*/类 CounterChild 扩展组件 {构造函数(道具){超级(道具);this.state = {count: 0//设置原始状态};}增加 = e =>{this.props.onUpdate(e.target.value = (this.state.count + 1))//传递给其他孩子和父母this.setState({count: this.state.count + 1});//设置新状态};减少 = e =>{this.props.onUpdate(e.target.value = (this.state.count - 1))this.setState({count: this.state.count - 1});};使成为() {返回 (<div>{this.state.count}
<button onClick={this.decrease.bind(this)}>-</button><button onClick={this.increase.bind(this)}>+</button>

);}}/* 以下用于加载产品列表*/var products = [[产品一", 24.99], [产品二", 9.99]];/* 产品列表结束*/class OtherChild 扩展 React.Component {使成为() {返回 (<div>{this.props.passedVal}

);}}/* 这是应用程序中计算价格乘以数量的部分*//*价格部分到此结束*//*本节用于计算出现在页面底部的总数*/var myTotal = 0;//变量来保存你的总数for (var i = 0, len = products.length; i < len; i++) {myTotal += products[i][1];//迭代你的第一个数组,然后获取第二个元素的值相加}/*总计算部分结束*/var productPrice = 0;//变量来保存你的总数for (var q = 0, pricelen = products.length; q

);});返回

{产品组件}

;}}/*产品信息显示结束*//*以下部分返回出现在屏幕上的最终输出*/返回 (<div className="应用程序"><div className="App-header"><img src={logo} className="App-logo" alt="logo"/><h2>欢迎反应</h2>

<div><测试产品={产品}/>£{myTotal}

);}}导出默认应用程序;

`如果代码混乱,我深表歉意,因为我说我对此很陌生.任何帮助将不胜感激

解决方案

查看下面的代码片段,我认为应该会有所帮助.

class App extends React.Component {状态 = {产品: [{title: 'Apple', count: 0, price: 100},{title: 'IBM', count: 0, price: 200},{title: 'HP', count: 0, price: 300},]}onChange = (index, val) =>{this.setState({产品: this.state.products.map((product, i) => (我 === 索引?{...product, count: val} : 产品))})}使成为 () {返回 (<div><ProductList products={this.state.products} onChange={this.onChange}/><总产品={this.state.products}/>

)}};const ProductList = ({ products, onChange }) =>(<ul>{products.map((product, i) => (<li key={i}>{产品名称}<输入类型=文本"价值={product.count}onChange={e =>onChange(i, parseInt(e.target.value) || 0)}/>))});const Total = ({ products }) =>(<h3>价格:{products.reduce((sum, i) => (sum += i.count * i.price), 0)})ReactDOM.render(, document.querySelector('#root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>

I'm an extremely new user to React and I'm having trouble with an app I'm trying to design. Basically I want a list of products that I can have the user update a quantity of, the total for each quantity will appear under the product and the total for the whole package will appear at the bottom. If anyone can help me with this it would be very much appreciated. My code is included below `

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

class App extends Component {


  render() {
    /* This is the Counter Part of the App used to denote the quantity of items*/
     class Counter extends React.Component {
      constructor(props) {
        super(props);

        this.state = {
          count: 0
        };
      }

      onUpdate = (val) => {
        this.setState({
          count: val
        });
      };

      render() {

        return (
          <div>
            <CounterChild onUpdate={this.onUpdate} />
            <br />
            <OtherChild passedVal={this.state.count} />
          </div>
        )
      }
    }
    /*Counter Section Ends here*/

    class CounterChild extends Component {
      constructor(props) {
        super(props);

        this.state = {
          count: 0 // Setting the Original State
        };
      }

      increase = e => {
        this.props.onUpdate(e.target.value  = (this.state.count + 1)) // Passed to Other child and Parent
        this.setState({count: this.state.count + 1}); // Setting the New State
      };

      decrease = e => {
        this.props.onUpdate(e.target.value  = (this.state.count - 1))
        this.setState({count: this.state.count - 1});
      };

      render() {
        return (
          <div>
            {this.state.count}<br />
            <button onClick={this.decrease.bind(this)}>-</button>
            <button onClick={this.increase.bind(this)}>+</button>
          </div>
        );
      }
    }

    /* The following is used to load the products list*/
    var products = [["product one", 24.99], ["product two", 9.99]];
    /* products list ends*/

    class OtherChild extends React.Component {
      render() {          
        return (
          <div>
            {this.props.passedVal}
          </div>
        );
      }
    }

    /* This is the section of the app which calculates the price times the quantity*/

    /*Price Section Ends here*/


    /*This section is used to calculate the total that appears at the bottom of the page*/
    var myTotal = 0; // Variable to hold your total

    for (var i = 0, len = products.length; i < len; i++) {
      myTotal += products[i][1]; // Iterate over your first array and then grab the second element add the values up
    }
    /*Total calculation section ends*/


    var productPrice = 0; // Variable to hold your total

    for (var q = 0, pricelen = products.length; q < pricelen; q++) {
      productPrice = products[q][1]; // Iterate over your first array and then grab the second element add the values up
    }




    /*The following section displays the product info in the app one line at a time*/
    class Test extends Component {
      render() {
        var productComponents = this.props.products.map(function(product) {

          return (
            <div className="product">
              {product[0]}<br />
              £{productPrice}<br />
              <Counter />
            </div>
          );
        });
        return <div>
        {productComponents}
        </div>;
      }

    }
    /*Product info display Ends*/

    /*The following section returnd the final output which appears on screen*/
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <div>
          <Test products={products} />
          £{myTotal}
        </div>

      </div>
    );
  }
}

export default App;

` I apologise if the code is messy, as I said I'm very new at this. Any assistance would be greatly appreciated

解决方案

Checkout the snippet below, I think it should help.

class App extends React.Component {
  state = {
    products: [
      {title: 'Apple', count: 0, price: 100},
      {title: 'IBM', count: 0, price: 200},
      {title: 'HP', count: 0, price: 300},
    ]
  }
  
  onChange = (index, val) => {
    this.setState({
      products: this.state.products.map((product, i) => (
        i === index ? {...product, count: val} : product
      ))
    })
  }

  render () {
    return (
      <div>
        <ProductList products={this.state.products} onChange={this.onChange} />
        <Total products={this.state.products} />
      </div>
    )
  }
};

const ProductList = ({ products, onChange }) => (
  <ul>
    {products.map((product, i) => (
      <li key={i}>
        {product.title}
        <input 
          type="text" 
          value={product.count}
          onChange={e => onChange(i, parseInt(e.target.value) || 0)}
        />
      </li>
    ))}
  </ul>
);

const Total = ({ products }) => (
  <h3>
    Price: 
    {products.reduce((sum, i) => (
      sum += i.count * i.price
    ), 0)}
  </h3>
)


ReactDOM.render(<App />, document.querySelector('#root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

这篇关于计算反应中的数量和总价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆