未能在反应组件内使用文档对象.“文档未定义"错误 [英] Failing to use document object inside of react component. "document is not defined" error
问题描述
我在 React 组件中使用了一些浏览器嗅探代码
import React, { useState } from 'react'const SomeComponent = ({props}) =>{const isIE = document.documentMode;返回 (<div>这里有一些浏览器嗅探代码.
)}
不过,我在构建时遇到此错误,文档未定义"
当我这样尝试时它也失败了
import React, { useState } from 'react'const isIE = document.documentMode;const SomeComponent = ({props}) =>{console.log(isIe)返回 (<div>这里有一些浏览器嗅探代码.
)}
我正在从下一个服务器中的 create-react-library 组件运行.
在 React 中访问文档对象的最佳方式是什么?
我在这里看到了一些浏览器嗅探反应代码,但它不起作用,因为我在构建时遇到错误 ReactJS 中的浏览器检测
当你使用 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) 返回空值;在这里返回<div>一些浏览器嗅探代码.</div>;};
I've got some browser sniffing code that I'm using inside of a react component
import React, { useState } from 'react'
const SomeComponent = ({props}) => {
const isIE = document.documentMode;
return (
<div>
Some browser sniffing code here.
</div>
)
}
I'm getting this error on build, though, "document is not defined"
It also fails when I try it like this
import React, { useState } from 'react'
const isIE = document.documentMode;
const SomeComponent = ({props}) => {
console.log(isIe)
return (
<div>
Some browser sniffing code here.
</div>
)
}
I'm running from a create-react-library component in a next server.
What's the best way to access the document object inside of react?
I've seen some browser sniffing react code here but it didn't work cause I got the errors on build Browser Detection in ReactJS
When you are using Next.js
, you should be aware that some of your code will be run in the server-side where window
, document
and other browser specific APIs will be not available.
Since useEffect
hook only runs in the client-side, you can use it together with useState
to achieve your goal:
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>;
};
这篇关于未能在反应组件内使用文档对象.“文档未定义"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!