简体   繁体   English

从 HTML 插入按钮<script> tag in React.js

[英]Inserting button from HTML <script> tag in React.js

I'm trying to make use of the payment gateway API of a local company that is not specifically designed for React but instead, they provide a generic HTML fragment that inserts a button to proceed to their Checkout page, external to my site.我正在尝试利用一家本地公司的支付网关 API,该 API 不是专门为 React 设计的,而是提供了一个通用的 HTML 片段,该片段插入一个按钮以进入我网站外部的结帐页面。

This is the HTML fragment:这是 HTML 片段:

<form action="https://www.example.com/paymentsuccess" method="POST">
  <script
    src="https://www.mercadopago.com.ar/integrations/v1/web-tokenize-checkout.js"
    data-public-key="ENV_PUBLIC_KEY"
    data-transaction-amount="100.00">
  </script>
</form>

After the client enters the card's info (outside of my site), their API then makes a POST to my Node backend server (at "action" attribute) to give me some safe info needed to confirm the payment.在客户端输入卡的信息(在我的站点之外)后,他们的 API 会向我的 Node 后端服务器(在“action”属性中)发送一个 POST 请求,为我提供一些确认付款所需的安全信息。

I didn't considered pasting it in the public folder as it actually renders a button to redirect the user to an external page and the location of the button is critical.我没有考虑将它粘贴到公共文件夹中,因为它实际上呈现了一个按钮以将用户重定向到外部页面,并且按钮的位置至关重要。

This might be a too simple a question but I'm new to React, how could I insert this fragment/button in my frontend app with the info needed via it's attributes (public key/transaction amount)?这可能是一个太简单的问题,但我是 React 的新手,我怎么能在我的前端应用程序中插入这个片段/按钮,并通过它的属性(公钥/交易金额)提供所需的信息?

Any help to guide me in the right direction is highly appreciated.任何指导我朝着正确方向前进的帮助都受到高度赞赏。

Here is how you can render the button as a React component这是将按钮呈现为 React 组件的方法

    function PaymentForm (props) {
      const paymentForm = React.useRef(null);
      React.useEffect(() => {
      const script = document.createElement("script");
      script.src = "https://www.mercadopago.com.ar/integrations/v1/web-tokenize-checkout.js";
      script.setAttribute('data-public-key',"ENV_PUBLIC_KEY")
      script.setAttribute('data-transaction-amount',"100.00")
        console.log(paymentForm.current)
      paymentForm.current.appendChild(script)
    }, []);

    return (
       <form action="https://www.example.com/paymentsuccess" method="POST" ref={paymentForm}></form>);
    }

Note that it will load the script once when the component mounts.请注意,它会在组件挂载时加载一次脚本。 Depending on your situation you might want to re-render the button when the amount value changes, in which case add it as a condition to useEffect (you might need to delete the previous one).根据您的情况,您可能希望在数量值更改时重新呈现按钮,在这种情况下,将其添加为 useEffect 的条件(您可能需要删除前一个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM