You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js的.jsx/.tsx文件中插入纯HTML代码(以Razorpay为例)

Next.js嵌入Razorpay订阅按钮代码方案

你提供的原始HTML代码不能直接复制到JSX/TSX中使用,React会默认忽略JSX内的普通<script>标签不会执行,以下是两种可直接用的实现方案:


方案1:使用Next.js官方Script组件(推荐)

这是Next.js官方推荐的第三方脚本加载方案,支持自定义加载策略,避免阻塞页面渲染。

适配App Router(Next.js 13+)

需在组件顶部标注'use client'声明为客户端组件:

'use client'
import Script from 'next/script'

export default function RazorpaySubscriptionBtn() {
  return (
    <form>
      <Script
        src="https://cdn.razorpay.com/static/widget/subscription-button.js"
        data-subscription_button_id="pl_I3alndvIjA9dQW"
        data-button_theme="brand-color"
        strategy="afterInteractive"
        async
      />
    </form>
  )
}

适配Pages Router

无需客户端声明,直接引入使用即可:

import Script from 'next/script'

export default function SubscriptionPage() {
  return (
    <div>
      {/* 你页面的其他内容 */}
      <form>
        <Script
          src="https://cdn.razorpay.com/static/widget/subscription-button.js"
          data-subscription_button_id="pl_I3alndvIjA9dQW"
          data-button_theme="brand-color"
          strategy="lazyOnload"
          async
        />
      </form>
    </div>
  )
}

方案2:useEffect动态注入脚本

适合特殊场景下需要手动控制脚本注入时机的需求:

'use client'
import { useEffect, useRef } from 'react'

export default function RazorpaySubscriptionBtn() {
  const formRef = useRef<HTMLFormElement>(null)

  useEffect(() => {
    if (!formRef.current || formRef.current.querySelector('script')) return
    // 动态创建script标签
    const payScript = document.createElement('script')
    payScript.src = 'https://cdn.razorpay.com/static/widget/subscription-button.js'
    payScript.async = true
    payScript.setAttribute('data-subscription_button_id', 'pl_I3alndvIjA9dQW')
    payScript.setAttribute('data-button_theme', 'brand-color')
    formRef.current.appendChild(payScript)
  }, [])

  return <form ref={formRef} />
}

注意事项

  • Script组件的strategy属性可根据需求调整:afterInteractive为页面可交互后立即加载,lazyOnload为浏览器空闲时加载,beforeInteractive为页面可交互前加载(适合必须提前加载的核心脚本)
  • 不要修改Razorpay的data-*属性值,否则会导致按钮无法正常加载
  • 如果出现按钮重复渲染的问题,可在逻辑中加脚本加载状态判断,避免重复注入

内容的提问来源于stack exchange,提问作者user12449933

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:18:04