【发布时间】:2020-12-17 12:34:42
【问题描述】:
知道NextJS 正在使用服务器端渲染,我想使用SurveyJs 但surveyJS 正在使用一些必须在客户端执行的功能。就我而言,我想使用StylesManager.applyTheme,但它会引发ReferenceError: document is not defined的服务器错误
我可以使用任何可能的方式在客户端执行applyTheme 函数吗?
【问题讨论】:
知道NextJS 正在使用服务器端渲染,我想使用SurveyJs 但surveyJS 正在使用一些必须在客户端执行的功能。就我而言,我想使用StylesManager.applyTheme,但它会引发ReferenceError: document is not defined的服务器错误
我可以使用任何可能的方式在客户端执行applyTheme 函数吗?
【问题讨论】:
您可以通过创建一个使用外部函数来应用此主题的 useEffect Hook 来实现此目的:
import {useEffect} from 'react'
useEffect(() => {
const newSurveyCreator = new SurveyJSCreator.SurveyCreator('surveyCreatorContainer', surveyCreatorConfig);
newSurveyCreator.saveSurveyFunc = function() {
console.log(this);
console.log(this && this.text);
};
updateSurveyCreator(newSurveyCreator);
}, []);
【讨论】:
useEffect 钩子中执行了StylesManager.applyTheme 函数,它起作用了。
为了更好地实现,我使用来自 NextJs 的动态导入解决了这个问题
相反,我像这样导入了我的SurveyComponent:
const SurveyComponent = dynamic(
() => import("../../../../components/survey/PartOne"),
{
ssr: false,
}
);
确保我的SurveyComponent 不会在服务器端呈现。
【讨论】: