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

ReactJS教程:如何向PayPal按钮组件传递数据?

How to Dynamically Pass Product Data to Your PayPal Button Component

Great question! Right now your PayPal component uses hardcoded values, but we can easily modify it to accept dynamic data from your cart page. Here's a step-by-step solution tailored to your setup:

1. Update the PayPal Component to Accept Props

First, modify your Paypal component to take in dynamic values as props. We'll add props for description, amount, and an optional currency (with a default of EUR to keep things flexible):

import React, { useEffect, useRef } from 'react';

// Accept dynamic props from the parent component
export default function Paypal({ description, amount, currency = 'EUR' }) {
  const paypal = useRef();

  useEffect(() => {
    // Create the PayPal buttons instance
    const paypalButtons = window.paypal.Buttons({
      style: {
        color: 'gold',
      },
      createOrder: (data, actions) => {
        return actions.order.create({
          intent: 'CAPTURE',
          purchase_units: [
            // Replace hardcoded values with props
            { 
              description: description, 
              amount: { 
                currency_code: currency, 
                value: amount 
              } 
            }
          ]
        });
      },
      onApprove: (data, actions) => {
        console.log("Transaction Réussite");
        return actions.order.capture();
      },
      onCancel: (data, actions) => {
        // Optional: Add logic for cancelled transactions here
      }
    }).render(paypal.current);

    // Cleanup: Destroy old buttons when props change or component unmounts
    return () => {
      if (paypalButtons) {
        paypalButtons.close();
      }
    };
  // Re-run the effect whenever props update
  }, [description, amount, currency]);

  return (
    <div ref={paypal}></div>
  );
}

2. Pass Dynamic Data from Your Cart Page

Now in your panierPage, you can pass real cart data to the PayPal component. For example, if you have cart items stored in state, calculate the total amount and generate a combined description:

import PayPal from '../services/PayPal/paypal';
import { useState } from 'react';

export default function panierPage() {
  // Example: Replace with your actual cart state/data
  const [cartItems, setCartItems] = useState([
    { name: 'Une table', price: 10.00 },
    { name: 'Deux chaises', price: 8.50 }
  ]);

  // Calculate total (format to 2 decimal places as required by PayPal)
  const totalAmount = cartItems.reduce((sum, item) => sum + item.price, 0).toFixed(2);
  
  // Create a combined description of all cart items
  const productDescription = cartItems.map(item => item.name).join(', ');

  return (
    <Grid style={{marginLeft: '2%'}}>
      {/* Pass dynamic props to the PayPal component */}
      <PayPal 
        description={productDescription} 
        amount={totalAmount} 
        // currency="USD" // Optional: Override default if needed
      />
    </Grid>
  );
}

Key Details to Keep in Mind:

  • PayPal Amount Requirements: Always pass the amount as a string with exactly two decimal places (e.g., "10.00" instead of 10). The toFixed(2) method handles this perfectly.
  • Cleanup Logic: The close() method in the cleanup function ensures old button instances are removed when props change, preventing duplicate buttons or unexpected behavior.
  • Extensibility: If you need to pass more detailed item breakdowns, you can extend the purchase_units object to include individual items—just adjust the props and payload accordingly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:58:15