小编Dan*_*ang的帖子

Nextjs 未按预期渲染并抛出“警告 Prop `style` 不匹配。” 使用内联样式时

问题描述

我的 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)

预期和实际结果 …

reactjs next.js

8
推荐指数
1
解决办法
1万
查看次数

标签 统计

next.js ×1

reactjs ×1