簡體   English   中英

如何在 react .js 文件中導入帶有腳本的 html 文件?

[英]How to import an html file with script in react .js file?

在我使用 nodejs 的 Reactjs 項目中,我試圖集成 paypal。 所以我用 paypal 按鈕創建了.html文件,我需要的是將這個 paypal 按鈕放在我的一個 js 文件中。 在此處輸入圖片說明

如圖所示,我需要渲染貝寶按鈕,我擁有的是:

測試.html

    <div id="paypal-button"></div>
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>
    <script>
           paypal.Button.render(
{
  // Configure environment
  env: "sandbox",
  client: {
    sandbox: "demo_sandbox_client_id",
    production: "demo_production_client_id"
  },
  // Customize button (optional)
  locale: "en_US",
  style: {
    size: "small",
    color: "gold",
    shape: "pill"
  },

  // Enable Pay Now checkout flow (optional)
  commit: true,

  // Set up a payment
  payment: function(data, actions) {
    return actions.payment.create({
      transactions: [
        {
          amount: {
            total: "0.01",
            currency: "USD"
          }
        }
      ]
    });
  },
  // Execute the payment
  onAuthorize: function(data, actions) {
    return actions.payment.execute().then(function() {
      // Show a confirmation message to the buyer
      window.alert("Thank you for your purchase!");
    });
  }
},
"#paypal-button"
);

支付選項.js

  import htmlContent from "path to/test.html";----->Trying to import that html file but fails with error.
 render = () => {
       <div className="ui middle aligned animated celled selection list">
                      {payment.cards.map(card => (
                        <div
                          className={
                            (selectedCard === card._id ? "disabled " : "") +
                            "item"
                          }
                          key={card._id}
                          onClick={() => {
                            selectCard(card._id);
                          }}
                        >
                          {selectedCard === card._id && (
                            <i className="green check icon" />
                          )}
                          <div className="content">
                            <div className="header">
                              {card.brand} ending in {card.last4}
                            </div>
                            {card.name && (
                              <div className="description">
                                Name: {card.name}
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                      <div
                        className={
                          ("" === selectedCard ? "disabled " : "") + "item"
                        }
                        key="newCard"
                        onClick={() => {
                          selectCard("");
                        }}
                      >
                        {"" === selectedCard && (
                          <i className="green check icon" />
                        )}
                        <div className="content">
                          <div className="header">New card</div>
                        </div>
                      </div>

                      <div
                        className={
                          (selectedCard === "paypal" ? "disabled " : "") +
                          "item"
                        }
                        key="paypal"

                      >
                        {selectedCard === "paypal" && (
                          <i className="green check icon" />
                        )}
                        <div className="content">
                          Paypal

                        </div>
                      </div>
                    </div>
 }

錯誤是:

   Module parse failed: Unexpected token (1:0)
   You may need an appropriate loader to handle this file type.
   | <div id="paypal-button"></div>
   | <script src="https://www.paypalobjects.com/api/checkout.js"></script>
   | <script>

我該如何解決這個問題並執行我的貝寶按鈕?

您可以使用react-async-script-loader

由於您正在研究 reactjs 產品,因此您可以編寫一個 react 組件來執行相同的操作,而不是使用 HTML 文件。

這里https://cubettech.com/resources/blog/integrating-paypal-rest-api-with-react-js/是一個很好的例子。

貝寶組件:

import React from 'react';
import ReactDOM from 'react-dom';
import scriptLoader from 'react-async-script-loader';
import PropTypes from 'prop-types';

class PaypalButton extends React.Component {
    constructor(props) {
        super(props);
        window.React = React;
        window.ReactDOM = ReactDOM;
        this.state = {
            showButton: false,
            env: 'sandbox', // Or 'sandbox'
            client: {
                sandbox: 'xxxxxxxxx', // sandbox client ID
                production: 'xxxxxxxxx' // production client ID
            },
            commit: true, // Show a 'Pay Now' button
        };
    }

    componentDidMount() {
        const {isScriptLoaded, isScriptLoadSucceed} = this.props;
        if (isScriptLoaded && isScriptLoadSucceed) {
            this.setState({showButton: true});
        }
    }

    componentWillReceiveProps({isScriptLoaded, isScriptLoadSucceed}) {
        if (!this.state.show) {
            if (isScriptLoaded && !this.props.isScriptLoaded) {
                if (isScriptLoadSucceed) {
                    this.setState({showButton: true});
                } else {
                    console.log('Cannot load Paypal script!');
                    this.props.onError();
                }
            }
        }
    }

    render() {
        const payment = () => paypal.rest.payment.create(this.props.env, this.props.client, {
            transactions: [
                {amount: {total: this.props.total, currency: this.props.currency}},
            ],
        });

        const onAuthorize = (data, actions) => actions.payment.execute().then(() => {
            const payment = Object.assign({}, this.props.payment);
            payment.paid = true;
            payment.cancelled = false;
            payment.payerID = data.payerID;
            payment.paymentID = data.paymentID;
            payment.paymentToken = data.paymentToken;
            payment.returnUrl = data.returnUrl;
            this.props.onSuccess(payment);
        });

        let ppbtn = '';
        if (this.state.showButton) {
            ppbtn = (<paypal.Button.react
                env={this.state.env}
                client={this.state.client}
                payment={payment}
                commit
                onAuthorize={onAuthorize}
                onCancel={this.props.onCancel}
            />);
        }
        return <div>{ppbtn}</div>;
    }
}

PaypalButton.propTypes = {
    currency: PropTypes.string.isRequired,
    total: PropTypes.number.isRequired,
    client: PropTypes.object.isRequired,
};

PaypalButton.defaultProps = {
    env: 'sandbox',
    onSuccess: (payment) => {
        console.log('The payment was succeeded!', payment);
    },
    onCancel: (data) => {
        console.log('The payment was cancelled!', data);
    },
    onError: (err) => {
        console.log('Error loading Paypal script!', err);
    },
};

export default scriptLoader('https://www.paypalobjects.com/api/checkout.js')(PaypalButton);

應用組件

import React from 'react';
import PaypalExpressBtn from './PayPalExpressCheckOut';

export default class MyApp extends React.Component {
    render() {      
        const onSuccess = (payment) => {
            console.log("Your payment was succeeded!", payment);
        }           
        const onCancel = (data) => {
            // User pressed "cancel" or close Paypal's popup! 
            console.log('You have cancelled the payment!', data);
        }           
        const onError = (err) => {
 // The main Paypal's script cannot be loaded or somethings block the loading of that script! 
            console.log("Error!", err);
// Since the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js" 
// => sometimes it may take about 0.5 second for everything to get set, or for the button to appear          
        }                   
        let currency = 'USD'; // or you can set this value from your props or state   
        let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout 
 return (
            <PaypalExpressBtn 
currency={currency}
total={total}
onError={onError}
onSuccess={onSuccess}
onCancel={onCancel}
 />
        );
    }  
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM