如何在 React 组件中添加 Stripe.js 脚本

How to add Stripe.js script in React component

我想使用 Stripe 作为支付提供商创建一个支付表单。

Stripe.js Reference 中,使用 jQuery 描述了创建表单组件的过程,包括页面中的外部脚本。如何将它包含在我的 React 组件中?什么是最好的方法?到目前为止,我有以下内容:

import React, { Component } from 'react';

class PaymentForm extends Component {
 constructor(props) {
  super(props);
 }

 componentDidMount() {
   Stripe.setPublishableKey('THE-PUBLIC-KEY');
 }

 handleSubmit(e) {
   e.preventDefault();
   Stripe.card.createToken(e.currentTarget, (status, response) => {
    console.log( status, response );
   });
 }

 render() {
   //THE PAYMENT FORM
 }
}

注意 1:我不想使用 ReactScriptLoader,因为它没有主动更新。

注意 2:还看到了 解决方案,但我认为这不是好的做法。

虽然 Stripe 有 NPM module,但他们不支持将其用于客户端应用程序。您必须通过脚本标签将 stripe.js 库添加到您的 index.html 页面(或者在您生成 React 将挂载到并导入 React 脚本的 HTML 元素的任何地方):

<script src="https://js.stripe.com/v3/"></script>

这是 Stripe documentation 推荐的方法。它将在全局范围内创建 Stripe 对象,您的 React 代码可以访问它。

我会非常谨慎地使用图书馆以其开发人员支持的方式以外的任何方式进行支付 - 认为您为此目的避免 ReactScriptLoaderdangerouslySetInnerHtml 是正确的。

如果你使用 ESLint,你可以在你的 JSX 文件的顶部指定一个全局变量来停止警告:

/* global Stripe */

Stripe 已正式发布 react-stripe-elements module with React components that help you add Stripe Elements 到您的 React 应用程序。