在 React 中使用 Emotion 进行样式设置时,“:nth-child”在执行服务器端渲染错误时可能不安全

nor*_*ial 9 css emotion reactjs storybook

在React项目中使用Emotion,我正在设计一个特定元素的样式,如下所示:divpadding-bottom

export const StyledItem = styled('div')(() => ({
  '&:nth-child(1) > div:nth-child(1)': {
    paddingBottom: '1px'
  }
}))
Run Code Online (Sandbox Code Playgroud)

并在Chrome的控制台中收到以下错误消息:

进行服务器端渲染时,伪类":nth-child"可能不安全。尝试将其更改为":nth-of-type".

请参阅控制台的屏幕截图:

错误截图

以下更改解决了该问题并从控制台中删除了错误消息:

export const StyledItem = styled('div')(() => ({
  '&:nth-of-type(1) > div:nth-of-type(1)': {
    paddingBottom: '1px'
  }
}))
Run Code Online (Sandbox Code Playgroud)

查看package.json的依赖关系:

"dependencies": {
   "@emotion/core": "^10.0.28",
   "@emotion/styled": "^10.0.27",
   "react": "^16.13.1",
   "@storybook/react": "^5.3.13",
   /* other dependencies */
}
Run Code Online (Sandbox Code Playgroud)

问题:

因此,建议对错误消息进行更改解决了该问题。还检查了这个问题这个 GitHub 问题已经没有给我一个明确的解释。

问题是,如果事情发生在客户端而不是服务器端,为什么会显示该错误消息?谢谢你!

小智 8

当 SSR 渲染组件时,它也会随之渲染样式元素。组件的第一个子元素可能是样式元素,并且使用n-th-child可能不安全,因为它会是意外行为。

EmotionJS GitHub 问题