我的 nextjs 应用程序遇到问题。在某些组件中,我想在 CSR/SSR 之间添加一些不同的样式/类名。这是我的问题的简化演示代码。
索引.jsx
import React, { useEffect, useState } from 'react'
export default function index() {
const [isServer, setIsServer] = useState(typeof window === 'undefined')
const style = {
color: isServer ? 'red' : 'yellow',
}
console.log('SeverSide: isServer', isServer)
useEffect(() => {
setIsServer(typeof window === 'undefined')
console.log('ClientSide: isServer', isServer)
}, [])
return (
<div>
<h1 style={style}>Hi I am Danny</h1>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
使用 npx create-npx-app 构建的演示项目
"dependencies": {
"next": "11.1.2",
"react": "17.0.2",
"react-dom": "17.0.2"
}
Run Code Online (Sandbox Code Playgroud)