【发布时间】:2021-05-15 11:50:39
【问题描述】:
大家好,我是 React 的新手。我正在使用 typescript 构建我的 react 应用程序,并希望添加 Stripe 来进行在线支付。但是我找不到关于stripe的打字稿教程,所以我尝试使用javascript来编写stripe部分。但是当我触发条纹时。出现以下错误:
参考 stackOverFlow 上的其他解决方案,我使用了不同的导入方法,例如
import stripe from './stripe';
import * as stripe from './stripe';
但是没有一个能解决我的问题。
我的代码有什么问题?
代码如下: 对于条纹文件:
import React from 'react'
import { Element } from "@stripe/react-stripe-js"
import { loadStripe } from '@stripe/stripe-js'
import "./Stripe.css"
const PaymentForm = require ('./PaymentForm.js')
const PUBLIC_KEY = "pk_test_XXXXXXX"
const stripeTestPromise = loadStripe(PUBLIC_KEY)
export default function Stripe() {
return (
<Element stripe={stripeTestPromise}>
<PaymentForm />
</Element>
)
}
支付来自文件:
import React, { useState } from 'react'
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"
import * as axios from 'axios'
import "./Stripe.css"
const CARD_OPTIONS = {
iconStyle: "solid",
style: {
base: {
iconColor: "#c4f0ff",
color:"fff",
fontWeight: 500,
fontSize: "16px",
fontSmoothing:"antialiased",
},
invaild: {
iconColor: "#ffc7ee",
color: "ffc7ee"
}
}
}
export default function PaymentForm() {
const [success, setSuccess] = useState(false)
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async (e) => {
e.preventDefault()
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
})
if (!error) {
try {
const { id } = paymentMethod
const response = await axios.post('http://localhost:8080/checkout', {
amount: 500,
id
})
if (response.data.success) {
console.log('Successful payment')
setSuccess(true)
}
} catch (error) {
console.log('Error', error)
}
} else {
console.log(error.message)
}
}
return (
<div>
{!success ?
<form onSubmit={handleSubmit}>
<fieldset className="FormGroup">
<div className="FormRow">
<CardElement options={CARD_OPTIONS} />
</div>
</fieldset>
<button>Pay</button>
</form >
:
<div>
<h2>You just bought a sweet saptula</h2>
</div>
}
</div>
)
}
【问题讨论】:
-
如果默认导出为
Stripe(带有大写字母 S),则您无法从中获取stripe,除非它也被导出。
标签: javascript reactjs typescript stripe-payments