gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:33:01 28 4
gpt4 key购买 nike

如何将这段代码仅放入我的一个 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(所有其他脚本标签都在其中)并且工作正常,但它出现在所有页面中。我希望它只出现在一个组件中,但我不知道该把它放在哪里。

我应该创建一个函数并将其放入其中吗?或者我应该以某种方式将它放在渲染部分下方?

最佳答案

要使其成为 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>
{!!error && <div>{error}</div>}
</div>
);
}

export default Button;

希望对您有帮助。

关于javascript - 如何将 Javascript 代码放入 React 组件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410717/

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