css - 尝试导入错误 : 'createGlobalStyle' is not exported from 'styled-components'

标签 css reactjs sass material-ui styled-components

我尝试从 styled-components 导入 createGlobalStyle,但它似乎不起作用。我安装了styled-components npm包,版本是@3.4.10。


const GlobalStyle = createGlobalStyle`
html {
    height: 100%
}
* {
    padding: 0;
    margin: 0
}

`
export default GlobalStyle

上面的代码是我尝试导入 createGlobalStyle 的地方

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import GlobalStyle from './theme/globalStyles'

ReactDOM.render(
  <React.StrictMode>
    <App />
    <GlobalStyle />
  </React.StrictMode>,
  document.getElementById('root')
)

这是我在其中使用 GlobalStyle 组件的 index.js 文件。

运行代码后出现以下错误:

./src/theme/globalStyles.js
Attempted import error: 'createGlobalStyle' is not exported from 'styled-components'.

非常感谢任何帮助

最佳答案

如果您使用 styled-components 版本 3.4.10,那么您必须使用 injectGlobal 而不是 createGlobalStyle,因为 createGlobalStyle 仅在 styled-components 的 v4 中发布。查看:[Deprecated] injectGlobal

因此,为了让您的代码正常工作,您必须更改一些内容:

import { injectGlobal } from 'styled-components';

const GlobalStyle = injectGlobal`
html {
    height: 100%
}
* {
    padding: 0;
    margin: 0
}
`

export default GlobalStyle

在你的 index.ts

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import GlobalStyle from './theme/globalStyles'

ReactDOM.render(
  <React.StrictMode>
    <GlobalStyle /> // this comes first
    <App />
  </React.StrictMode>,
  document.getElementById('root')
)

关于css - 尝试导入错误 : 'createGlobalStyle' is not exported from 'styled-components' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67771051/

相关文章:

javascript - Angular 2动态全局CSS

javaScript text.replace 仅替换我想要替换的单词之一

javascript - 预计 toHaveBeenCalledWith 不适用于最新的 CreateReactApp 设置

javascript - react : How do I pass props to state component?

javascript - 使用 Vue,我将如何根据某些逻辑/数据加载不同的 CSS 文件?

sass - 错误: Cannot find module 'gulp-sass'

sass - Gulp 不会刷新导入的 scss 文件的更改

css - 汉堡菜单在非视网膜屏幕上看起来模糊?

html - 页脚没有获得背景颜色?

reactjs - 使用 create-react-app 创建的应用程序无法编译(kleur' 未定义有效的 './colors' 目标)