【发布时间】:2021-01-14 10:37:19
【问题描述】:
我正在开发一个 ReactJS 项目,我想在其中集成条带以允许用户更新他们的订阅付款信息。
我正在关注https://stripe.com/docs/stripe-js/react 的指南,但我遇到了问题。
下面是我目前拥有的代码
const stripe = useStripe();
const elements = useElements();
const errorDialogueCleared = () => {
setAPIResult(null);
}
const stripePromise = loadStripe('my_test_key');
const baseStripeElementOptions = {
style: {
base: {
fontFamily: 'Oxanium',
fontSize: '16px',
color: '#000000',
'::placeholder': {
color: '#000000',
},
},
invalid: {
color: '#9e2146',
},
}
}
const handleSubmit = async (event) => {
// Block native form submission.
event.preventDefault();
if (!stripe || !elements) {
// Stripe.js has not loaded yet. Make sure to disable
// form submission until Stripe.js has loaded.
return;
}
// Get a reference to a mounted CardElement. Elements knows how
// to find your CardElement because there can only ever be one of
// each type of element.
const cardElement = elements.getElement(CardElement);
// Use your card Element with other Stripe.js APIs
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});
if (error) {
console.log('[error]', error);
} else {
console.log('[PaymentMethod]', paymentMethod);
}
};
return (
<div className='container-fluid'>
<div className="mainContentNoSidebar">
<TopNavBar displayTimePeriodButton={false} title='Update Account Information' />
<BreadcrumbNav menu_items={breadcrumbNav} />
<div className='contentWrapper'>
<div className='container'>
<h1>Update Account Information</h1>
<form onSubmit={handleSubmit} style={{width: '50%', marginLeft: 'auto', marginRight: 'auto'}}>
<Elements stripe={stripePromise}>
<CardElement options={baseStripeElementOptions} />
</Elements>
<button className='btn btn-primary'>Submit Payment Details</button>
</form>
</div>
</div>
</div>
<ErrorDialogue dialogClosed={errorDialogueCleared} api_result={currentError} />
</div>
)
}
但是,尽管感觉我已经按照文档进行操作,但在页面加载后立即收到以下错误:
错误:找不到元素上下文;你需要包装的部分 您在提供程序中调用 useStripe() 的应用
我的 CardElement 包含在 Elements 组件中,所以我不确定为什么会看到此错误。
【问题讨论】: