我在集成外部库“react-calendly”中的组件时遇到了一些麻烦,特别是 PopUpButton 小部件,它需要插入父 DOM 节点。我目前的理解是,我的问题是由 Next.js 使用 SSR 引起的,因此我无法访问浏览器。我该如何解决这个问题?作为参考,我的网站是一个非常简单的全栈应用程序,适合他的业务,而我是 React/全栈开发的新手。以下是呈现我的页面组件的应用程序部分的代码:
import '../styles/globals.css'
import styles from '../styles/App.module.css'
import Navbar from '../components/navbar'
import Footer from '../components/footer'
function MyApp({Component, pageProps}) {
return (
<div className={styles.app}>
<div>
<Navbar />
</div>
<div className={styles.body} id="body">
<Component props={pageProps} />
</div>
<div>
<Footer className={styles.footer}/>
</div>
</div>
)
}
export default MyApp
Run Code Online (Sandbox Code Playgroud)
这是我的特定页面组件的代码:
import styles from '../styles/Home.module.css'
import Head from 'next/head'
import { PopupButton } from 'react-calendly'
export default function Home() {
return (
<div className="home">
<Head>
<title>Homepage</title>
</Head>
<div className="cal_div">
<PopupButton
url="https://calendly.com/my_url"
rootElement={document.getElementsById("body")}
text="Click here to schedule!"
/>
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我实际上设法针对完全相同的情况解决了这个问题next.js并且react.js
架构如下:
1. Calendly calling react component-> 2. dynamic calendly __next component->3. calendly child
1.React 父组件:
'use client';
import React from "react";
import CalendlyDynamic from "./Components/CalendlyDynamic";
export default function Home(){
return (
<div>
<CalendlyDynamic />
<div id="__next"></div>
</div>
)}
Run Code Online (Sandbox Code Playgroud)
1. -> 2.
Calendly 动态组件:
import dynamic from "next/dynamic";
const Calendly = dynamic(() => import("../Components/Calendly"), {
ssr: false
});
export default function Home() {
return (
<div>
<Calendly />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
2. -> 3.
日历的孩子
'use client'
import { PopupButton } from "react-calendly";
import { useEffect, useState } from "react";
export default function Calendly() {
const [rootElement, setRootElement] = useState(null);
useEffect(() => {
// Wait for the component to be mounted before setting the rootElement
if (typeof window !== "undefined") {
setRootElement(document.getElementById("__next"));
}
}, []);
return (
<div className="cal_div">
<PopupButton
className="rounded-md bg-primary py-4 px-8 text-base font-semibold text-white duration-300 ease-in-out hover:bg-primary/80"
url="https://calendly.com/your-link"
rootElement={rootElement}
text="Schedule Appointment"
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1095 次 |
| 最近记录: |