gpt4 book ai didi

javascript - React,在表单中加载脚本 (mercadopago)

转载 作者:行者123 更新时间:2023-12-05 07:02:47 25 4
gpt4 key购买 nike

我正在尝试实现一些支付系统 ( MercadoPago )。

根据文档,它只是粘贴这个:

<form method="POST">
<script
src="https://www.mercadopago.com.pe/integrations/v1/web-payment-checkout.js"
data-preference-id="589788715-2e52aeec-8275-487c-88ee-1a08cff37c08"
></script>
</form>

将它粘贴到一个纯 html 文件中效果很好:出现一个按钮并单击它会打开一个模式以按预期使用信用卡支付。然而,这在 React 中不起作用,因为它是动态加载脚本的。因此,我尝试使用效果 Hook 来插入 <script>这样加载:

const App = () => {
const setMercadoPagoPreferences = async () => {
const script = document.createElement('script');
script.src =
'https://www.mercadopago.com.ar/integrations/v1/web-payment-checkout.js';
script.async = true; // commenting or uncommenting seems to have no effect
script.setAttribute(
'data-preference-id',
'589788715-2e52aeec-8275-487c-88ee-1a08cff37c08'
);
document.getElementById('mercadoForm').appendChild(script);
};

useEffect(() => {
setMercadoPagoPreferences();
}, []);

return <form action='/procesar-pago' method='POST' id='mercadoForm' />;
};

这似乎正确加载了脚本,因为页面上附加了一个支付按钮。但是,单击它会打开一个模式,显示“哦不,发生了一些不好的事情”。这不会发生在我上面的 .html 示例中;所以这一定是因为 React 如何加载脚本或类似的东西。它不适用于开发或生产版本。

编辑:正如建议的那样,我尝试使用 refs 而不是直接附加子元素,但这似乎没有任何影响,它仍然不起作用。

最佳答案

我不知道这个框架,但也许就是这样:看起来这个人有类似的问题right here .

我认为存在问题,因为脚本未按时加载。所以也许让我们试试这个:

script.onload = () => {
document.getElementById('mercadoForm').appendChild(script);
};

此外,在 react ref 中有内置机制,如 HERE而不是 document.getElementById

关于javascript - React,在表单中加载脚本 (mercadopago),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63437991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com