在React中分配onChange事件时如何更新输入值?

时间:2020-01-06 07:57:40

标签: reactjs

我在CartHeader组件中的项目总数上遇到问题。显然,我已经添加了每种产品的数量,但结果却不是我预期的那样?谁能找到我的错?我真诚的感谢。

import ReactDOM from "react-dom";
import CartHeader from "./CartHeader";
import CartBody from "./CartBody";
import CartFooter from "./CartFooter";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [
        {
          id: 1,
          name: "Apple Watch Series 5",
          description: "Description for Apple Watch Series 5",
          img:
            "https://bachlongmobile.com/media/catalog/product/cache/2/image/040ec09b1e35df139433887a97daa66f/2/0/2076130625_1_1_1.jpg",
          price: 499.99,
          quantity: 1
        },
        {
          id: 2,
          name: "iPhone 11 Pro Max",
          description: "Description for iPhone 11 Pro Max",
          img:
            "https://cdn.fptshop.com.vn/Uploads/Originals/2019/9/11/637037687763926758_11-pro-max-xanh.png",
          price: 1099.99,
          quantity: 1
        },
        {
          id: 3,
          name: "Macbook Pro 16 inch",
          description: "Description for Macbook Pro 16 inch",
          img: "https://shopdunk.com/wp-content/uploads/2019/11/mac16inch.jpg",
          price: 2399.99,
          quantity: 1
        },
        {
          id: 4,
          name: "iPad Pro 12.9 inch",
          description: "Description for iPad Pro",
          img:
            "https://cdn.fptshop.com.vn/Uploads/Originals/2019/1/11/636828015979564724_ipad-pro-12-9-xam-1.png",
          price: 999.99,
          quantity: 1
        },
        {
          id: 5,
          name: "AirPods Pro",
          description: "Description for AirPods Pro",
          img:
            "https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/MWP22?wid=1144&hei=1144&fmt=jpeg&qlt=80&op_usm=0.5,0.5&.v=1572990352299",
          price: 249.99,
          quantity: 1
        }
      ]
    };
  }

  onRemoveProduct = id => {
    const newProducts = this.state.products;
    // Tìm vị trí sản phẩm cần xoá
    let index = newProducts.findIndex(product => product.id === id);
    // Kiểm tra nếu tìm thấy thì mới xoá
    if (index !== -1) {
      newProducts.splice(index, 1);
      this.setState({
        products: newProducts
      });
    }
  };

  handleChange = (e, id) => {
    const { products } = this.state;
    const indexProduct = products.findIndex(product => product.id === id);
    products[indexProduct].quantity = e.target.value;
    this.setState({ products });
  };

  render() {
    const products = this.state.products;
    let numberItems = 0;
    let subTotal = 0;
    products.map(product => {
      numberItems += product.quantity;
      subTotal += product.price * product.quantity;
    });

    return (
      <main>
        <CartHeader numberItems={numberItems} />
        <CartBody
          products={products}
          onRemoveProduct={this.onRemoveProduct}
          handleChange={this.handleChange}
        />
        <CartFooter subTotal={subTotal} />
      </main>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我曾经误解过这个问题。 链接代码和框: https://codesandbox.io/s/thirsty-hill-6w2ex

2 个答案:

答案 0 :(得分:1)

您应该为handleChange方法定义咖喱函数,如下所示:

  handleChange = id => e => {
    const {products} =  this.state;
    const indexProduct = products.findIndex(product => product.id === id);
    products[indexProduct].quantity = e.target.value;
    this.setState({ products: [...products] });
  };

内部CardBody:

  <input
      type="number"
      className="quantity"
      step={1}
      defaultValue={product.quantity}
      onChange={e => handleChange(product.id)(e)}
      />

在这里您可以找到codesandbox

答案 1 :(得分:0)

动态数据显示最好通过React状态完成。目前,您可以在render()函数中定义变量,但是此区域主要用于静态数据。

首先,将数值(数量和总计)定义为状态值而不是变量。然后,定义一个函数来处理每个产品的每个数量输入的onChange事件。在该函数中,处理每个数值的累加,然后用这些值更新状态。