Astro 在水合组件后未渲染 hCaptcha

问题描述 投票:0回答:1

我在 Astro 项目上渲染 hCaptcha 时遇到问题。刷新页面时,验证码字段会出现,然后消失。

index.astro

---
import Hcaptcha from "../components/hcaptcha.jsx";
---

<!doctype html>
<html lang="en">
  <head>
    <script src="https://js.hcaptcha.com/1/api.js" async defer></script>
  </head>
  <body>
    <Hcaptcha client:load />
  </body>
</html>

hcaptcha.jsx

import React from 'react';

const Hcaptcha = () => {
  return (
    <section className="websiteTitle__captcha">
      <div
        className="h-captcha"
        id="signupCaptcha"
        data-sitekey={import.meta.env.PUBLIC_MY_KEY}
        data-size="normal"
        data-theme="dark"
      ></div>
    </section>
  );
};

export default Hcaptcha;

astro.config.mjs

import { defineConfig } from "astro/config";
import react from "@astrojs/react";

import node from "@astrojs/node";

// https://astro.build/config
export default defineConfig({
  integrations: [react()],
  vite: {
    server: {
      watch: {
        usePolling: true,
      },
    },
  },
  output: "hybrid",
  adapter: node({
    mode: "standalone",
  }),
});

我在浏览器的开发人员工具中收到以下警告:

警告:没想到服务器 HTML 会在

<iframe>
中包含
<div>

警告:水合过程中发生错误。服务器 HTML 已替换为

<astro-island>
中的客户端内容。

未捕获错误:水合失败,因为初始 UI 与服务器上呈现的内容不匹配。

未捕获的错误:补水时出现错误。因为错误发生在 Suspense 边界之外,所以整个根将切换到客户端渲染。

这里有 StackBlitz 上的实时预览,您可以尝试一下。

删除客户端:加载修复了问题,并呈现验证码,但由于它没有水合,我无法真正使用它。

尝试从SSG切换到SSR,但没有效果。我在 WSL 上本地运行此代码。

reactjs astrojs hcaptcha
1个回答
1
投票

最有可能发生的事情是:

  1. 组件在服务器端渲染,并将 HTML 发送到客户端
  2. 执行 h-captcha 脚本并修改 HTML(例如插入 iframe)。
  3. React 尝试水合组件,期望来自服务器的原始 HTML,但找到了一个 iframe。这样你就可以得到
    Warning: Did not expect server HTML to contain a <iframe> in <div>.

长话短说,h-captcha 脚本不适合在没有任何包装器的情况下与 React 一起使用。

仅在服务器上渲染 HTML,或者如果您确实需要一些交互性,请使用类似 react-hcaptcha 的东西。

© www.soinside.com 2019 - 2024. All rights reserved.