基于 i18n 语言的 React Stripe Elements 占位符

问题描述

我想更改基于 i18n 语言的 CardElement 占位符。 我在加载条带时将语言环境作为选项传递

stripePromise = loadStripe(key,{   locale: i18nInstance.language })

它确实有效,但是当使用切换器更改语言时,它不会反映在占位符上。知道在 useEffect 中加载条纹有副作用,我如何相应地更新选项

解决方法

Stripe 还允许您像这样使用 Elements Props 插入语言环境:

<Elements stripe={stripePromise} options={ locale: i18nInstance.language }>

将区域设置添加到选项将使您更灵活地在组件内部而不是外部处理此值,因为它们建议 loadStripe

我没有为 i18n 使用相同的库,但这是 NextJs 和 TS 的示例

import React from 'react'
import {
  loadStripe,StripeElementLocale,} from '@stripe/stripe-js'
import { Elements } from '@stripe/react-stripe-js'
import { useRouter } from 'next/router'
import Checkout from 'library/organisms/Checkout'

// Make sure to call `loadStripe` outside of a component’s render to avoid
// recreating the `Stripe` object on every render.
const stripePromise = loadStripe('ADD YOUR KEY')

const CheckoutPage = () => {
  const { locale } = useRouter()

  // The following line has been simplified to only check if the locale is 'en'
  // so TS don't complain but you could develope it for more languages.
  const stripeLocale: StripeElementLocale = locale === 'en' ? locale : 'auto'

  return (
    <Elements stripe={stripePromise} options={ locale: stripeLocale }>
      <Checkout />
    </Elements>
  )
}

export default CheckoutPage