我有一些浏览器嗅探代码,我在一个反应性组件的内部使用
import React, { useState } from 'react'
const SomeComponent = ({props}) => {
const isIE = document.documentMode;
return (
<div>
Some browser sniffing code here.
</div>
)
}
但是,我在构建时得到了这个错误,“文档没有定义”
当我像这样尝试时,它也失败了。
import React, { useState } from 'react'
const isIE = document.documentMode;
const SomeComponent = ({props}) => {
console.log(isIe)
return (
<div>
Some browser sniffing code here.
</div>
)
}
我正在从下一个服务器中的创建-反应库组件中运行。
访问react内部的文档对象的最佳方法是什么?
我在这里看到了一些浏览器嗅探反应代码,但是它没有工作,因为我在构建Browser Detection in ReactJS时出现了错误
发布于 2020-07-10 01:02:20
当您使用Next.js时,您应该知道您的一些代码将在服务器端运行,在服务器端,window、document和其他浏览器特定的API将不可用。
由于useEffect钩子只在客户端运行,因此可以与useState一起使用它来实现目标:
import React, { useState, useEffect } from "react";
const SomeComponent = ({ props }) => {
const [isIE, setIsIE] = useState(false);
useEffect(() => {
setIsIE(document.documentMode);
}, []);
if (!isIE) return null;
return <div>Some browser sniffing code here.</div>;
};发布于 2020-07-10 02:29:51
Next.js是一个SSR框架,您的代码将同时运行在服务器端和客户端.在服务器端运行时不会定义Window。如果您想从window获得属性,可以尝试以下方法。
window如果(类型为窗口!==‘未定义’){ console.log(window.document) }
only。在这种情况下,您可以使用dynamic。components/ClientSideComponent
const ClientSideComponent = props => { //您可以直接在此组件console.log(window.document)返回窗口(只在客户端运行代码)}
页面/索引
从‘next/ dynamic’导入动态;const ClientSideComponent = dynamic(() => import (‘./components/ClientSideComponent’),{ ssr: false,});const HomePage = props => {next }
https://stackoverflow.com/questions/62822902
复制相似问题