如何将Javascript代码放入React的组件中?

时间:2019-06-01 21:56:03

标签: javascript reactjs stripe-payments

如何将这段代码放在我的一个React组件中?


<!--
  Create a button that your customers click to complete their purchase. Customize the styling to suit your branding.
-->
<button
  style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
  id="checkout-button-sku_FAe7tbPK29byHW"
  role="link"
>
  Checkout
</button>

<div id="error-message"></div>

<script>
  var stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");
  var checkoutButton = document.getElementById(
    "checkout-button-sku_FAe7tbPK29byHW"
  );
  checkoutButton.addEventListener("click", function() {
    stripe
      .redirectToCheckout({
        items: [{ sku: "sku_FAe7tbPK29byHW", quantity: 1 }],
        successUrl:
          window.location.protocol + "//www.jobdirecto.com/jobConfirm",
        cancelUrl: window.location.protocol + "//www.jobdirecto.com/errorPage"
      })
      .then(function(result) {
        if (result.error) {
          var displayError = document.getElementById("error-message");
          displayError.textContent = result.error.message;
        }
      });
  });
</script>

目前,它位于index.js(所有其他脚本标签所在的位置)中,并且可以正常工作,但是它出现在所有页面中。我希望它仅出现在一个组件中,但我不确定将其放置在何处。

我应该创建一个函数并放在里面吗?还是应该以某种方式将其放在渲染部分下面?

1 个答案:

答案 0 :(得分:1)

要使其成为一个React组件,它将变成这样:

import React, { useState } from 'react';

function Button() {
  const stripe = Stripe('pk_live_5PjwBk9dSdW7htTKHQ3HKrTd');

  const [error, setError] = useState();

  const handleClick = () => {
    stripe
      .redirectToCheckout({
        items: [{ sku: 'sku_FAe7tbPK29byHW', quantity: 1 }],
        successUrl: window.location.protocol + '//www.jobdirecto.com/jobConfirm',
        cancelUrl: window.location.protocol + '//www.jobdirecto.com/errorPage'
      }).then((result) => {
        if (result.error) {
          setError(result.error.message);
        }
      });
  }

  return (
    <div>
      <button onClick={handleClick}>Checkout</button>
      <div>{error}</div>
    </div>
  );
}

export default Button;

希望它对您有帮助。