You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React购物车CartItem组件无法获取函数及商品属性显示如何修复?

问题排查与修复方案

核心问题点

  • 操作函数透传链路断裂:CartItem中尝试读取props.value获取增减、删除函数,但父组件CartList未将上层传入的包含操作函数的value属性传递给CartItem,导致函数读取失败
  • 按钮未绑定操作事件:加减按钮没有绑定对应的decrement、increment点击事件,点击无响应
  • 样式拼写错误:图片样式中height拼写为heigth,样式不生效

修复后代码

CartList.js

import React from "react";
import CartItem from "./CartItem";

export default function CartList(props) {
  const { items, value } = props;
  console.log(props, "inside cart");
  return (
    <div>
      {items.cart.map((item) => (
        <CartItem key={item.id} item={item} value={value} />
      ))}
    </div>
  );
}

CartItem.js

import React from "react";

function CartItem(props) {
  
  const { id, title, img, price, total, count } = props.item;
  const { increment, decrement, removeItem } = props.value;

  return (
    <div className="row my-1 text-capitalize text-center">
      <div className="col-10 mx-auto col-lg-2">
        <img
          src={img}
          style={{ width: "5rem", height: "5rem" }}
          className="img-fluid"
          alt=""
        />
      </div>
      <div className="col-10 mx-auto col-lg-2 ">
        <span className="d-lg-none">product :</span> {title}
      </div>
      <div className="col-10 mx-auto col-lg-2 ">
        <strong>
          <span className="d-lg-none">price :</span> ${price}
        </strong>
      </div>
      <div className="col-10 mx-auto col-lg-2 my-2 my-lg-0 ">
        <div className="d-flex justify-content-center">
          <div>
            <span className="btn btn-black mx-1" onClick={() => decrement(id)}>-</span>
            <span className="btn btn-black mx-1">{count}</span>
            <span className="btn btn-black mx-1" onClick={() => increment(id)}>+</span>
          </div>
        </div>
      </div>
      <div className="col-10 mx-auto col-lg-2 ">
        <div className=" cart-icon" onClick={() => removeItem(id)}>
          <i className="fas fa-trash" />
        </div>
      </div>

      <div className="col-10 mx-auto col-lg-2 ">
        <strong>item total : ${total} </strong>
      </div>
    </div>
  );
}

export default CartItem;

生效验证

确认CartList的上层父组件已正确将包含increment、decrement、removeItem三个函数的value属性传入CartList后,商品属性渲染、购物车操作功能均可正常运行。

内容的提问来源于stack exchange,提问作者na ha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:45:05