Home / 指南 / React 联系表单集成(Vite 和单页应用程序)
集成指南 · REACT 和 SPA

React 联系表单集成(Vite 和单页应用程序)

如何将联系和反馈表单添加到使用 Vite 或 Create React App 构建的 React 单页应用程序 (SPA),具有蜜罐垃圾邮件防御和即时收件箱通知功能。

1.带有Vite的标准React联系表单组件

这个轻量级 React 组件使用标准 React hooks (useState) 和浏览器 Fetch API 直接提交到您的 Lugatu 公共端点。 不需要外部表单库或后端服务器。

src/components/ContactForm.tsx tsx
import React, { useState } from 'react';

export function ContactForm() {
  const [formData, setFormData] = useState({ name: '', email: '', message: '', _gotcha: '' });
  const [status, setStatus] = useState<'idle' | 'submitting' | 'success' | 'error'>('idle');
  const [errorMessage, setErrorMessage] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (formData._gotcha) return; // Silent discard for automated bot traps

    setStatus('submitting');
    setErrorMessage('');

    try {
      const response = await fetch('https://www.lugatu.com/api/v1/public/forms/YOUR_PUBLIC_FORM_ID/submissions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          fields: {
            name: formData.name,
            email: formData.email,
            message: formData.message,
          },
          honeypot: formData._gotcha,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to deliver message');
      }

      setStatus('success');
      setFormData({ name: '', email: '', message: '', _gotcha: '' });
    } catch (err: any) {
      setStatus('error');
      setErrorMessage(err.message || 'Submission error. Please try again.');
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4 max-w-md">
      <div>
        <label htmlFor="react-name" className="block text-sm font-semibold mb-1">Your Name</label>
        <input
          id="react-name"
          type="text"
          required
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          className="w-full border rounded-xl p-2.5"
        />
      </div>

      <div>
        <label htmlFor="react-email" className="block text-sm font-semibold mb-1">Email Address</label>
        <input
          id="react-email"
          type="email"
          required
          value={formData.email}
          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
          className="w-full border rounded-xl p-2.5"
        />
      </div>

      <div>
        <label htmlFor="react-message" className="block text-sm font-semibold mb-1">Message</label>
        <textarea
          id="react-message"
          rows={4}
          required
          value={formData.message}
          onChange={(e) => setFormData({ ...formData, message: e.target.value })}
          className="w-full border rounded-xl p-2.5"
        />
      </div>

      <!-- Honeypot spam defense -->
      <input
        type="text"
        name="_gotcha"
        value={formData._gotcha}
        onChange={(e) => setFormData({ ...formData, _gotcha: e.target.value })}
        style={{ display: 'none' }}
        tabIndex={-1}
        autoComplete="off"
      />

      <button
        type="submit"
        disabled={status === 'submitting'}
        className="btn-primary-editorial py-2.5 px-6"
      >
        {status === 'submitting' ? 'Sending...' : 'Send Message'}
      </button>

      {status === 'success' && (
        <p className="text-sm text-green-700 font-medium">Thank you! Your message was delivered.</p>
      )}
      {status === 'error' && (
        <p className="text-sm text-red-600">{errorMessage}</p>
      )}
    </form>
  );
}

2. 与 React Hook Form 和 Formik 集成

Lugatu 标准 JSON 提交模型可以轻松地与 React Hook Form、Formik 或 Zod 等表单验证库集成。 将序列化值直接传递到字段有效负载对象中。

useLugatuForm.ts typescript
// React Hook Form submission handler
const onSubmit = async (data: FormValues) => {
  const res = await fetch(`https://www.lugatu.com/api/v1/public/forms/${import.meta.env.VITE_LUGATU_FORM_ID}/submissions`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ fields: data }),
  });
  return res.ok;
};

3.React中的环境变量&秘密分离

在Vite中,公共变量以VITE_为前缀。 使用 VITE_LUGATU_FORM_ID 作为公共表单 ID。 切勿在客户端源代码或存储库中公开服务器到服务器 API 密钥 (lug_live_...)。

warning

以 lug_live_ 开头的实时 API 密钥严格保留用于服务器到服务器的执行。 任何使用实时 API 密钥发送的浏览器请求都会被拒绝并显示 HTTP 403。

安全和身份验证不变

安全不变:切勿使用 VITE_ 或 REACT_APP_ 作为实时 API 密钥的前缀。 浏览器客户端必须专门提交到没有 API 密钥的公共端点。

故障排除和常见摄取错误

表单提交在浏览器控制台中返回 CORS 错误

确保您提交到公共端点 (https://www.lugatu.com/api/v1/public/forms/YOUR_PUBLIC_FORM_ID/submissions)。 服务器到服务器端点 (POST /api/v1/forms/{id}/submissions) 显式阻止浏览器来源。

常见问题解答

我可以将 React Hook Form 或 Formik 与 Lugatu 一起使用吗?

是的。 Lugatu 接受带有 fields 对象的标准 JSON。 任何 React 表单库都可以序列化其值并提交到公共端点。

准备好创建您的表单端点了吗?

几秒钟内免费开始使用。 无需信用卡。

免费开始 →