【问题标题】:Typescript with react-stripe-elements does not pass injected props带有 react-stripe-elements 的打字稿不通过注入的道具
【发布时间】:2021-03-01 16:56:25
【问题描述】:

这是与 Stripe 相关的代码。

据我了解,错误TypeScript 认为CheckoutForm 需要stripe 道具,但它不是通过InjectedCheckoutForm 组件提供的。

另一方面,injectStripe 应该将 props stripeelements 注入到作为 elements 的子组件的包装组件中。 https://github.com/stripe/react-stripe-elements#setting-up-your-payment-form-injectstripe

type CreditCardProps = {
  secret: string
}

function StripeSection(props: CreditCardProps) {
  const { secret } = props

  return (
    <StripeProvider apiKey="pk_test_...">
      <Elements>
        <InjectedCheckoutForm secret={secret} />
      </Elements>
    </StripeProvider>
  )
}

type CheckoutFormProps = {
  stripe: ReactStripeElements.StripeProps
  secret: string
}

function CheckoutForm(props: CheckoutFormProps) {
  const { stripe, secret } = props
  const handleSubmit = async (
    event: React.FormEvent<HTMLFormElement>
  ): Promise<void> => {
    event.preventDefault()

    const result = await stripe.confirmCardSetup(secret, {})
  }

  return (
    <form className="form" onSubmit={handleSubmit}>
      <CardSection />
      <button>Submit</button>
    </form>
  )
}

const InjectedCheckoutForm = injectStripe(CheckoutForm)

function CardSection() {
  return (
    <div>
      <label>Card details</label>
      <CardElement
        style={{ base: { fontSize: '18px', backgroundColor: 'white' } }}
      />
    </div>
  )
}

我收到以下错误:

Property 'stripe' is missing in type '{ secret: string; }' but required in type 'CheckoutFormProps'.

【问题讨论】:

    标签: reactjs typescript stripe-payments


    【解决方案1】:

    现在InjectedCheckoutForm 组件的类型定义将是:

    const InjectedCheckoutForm: React.ComponentType<CheckoutFormProps>
    

    出现问题是因为 InjectedCheckoutForm 本身并不期望 stripe 道具 - 因为它是将该道具注入其子级的那个(即 CheckoutFormComponent

    解决方法是定义 InjectedCheckoutForm 组件的预期类型并将它们作为类型参数传递,如下所示:

    const InjectedCheckoutForm = injectStripe<{ secret: string }>(CheckoutForm);
    

    这将导致 InjectedCheckoutForm 的类型定义如下:

    const InjectedCheckoutForm: React.ComponentType<{
      secret: string;
    }>
    

    该组件接收您编写的秘密,它向其中注入条纹 CheckoutForm 组件并沿着秘密转发!

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 2020-10-19
      • 2021-02-28
      • 2020-02-01
      • 1970-01-01
      • 2015-10-23
      • 2016-08-08
      • 2020-09-21
      相关资源
      最近更新 更多