Attempted import error: 'injectGlobal' is not exported from 'styled-components' 在styled-component的解决

一、问题的出现:
  1. 在之前的项目开发中,在使用 styled-components 时,使用injectGlobal 定义样式变量时,出现了这个错误,Attempted import error: 'injectGlobal' is not exported from 'styled-components'
二、问题的分析及解决:
  1. 这个问题出现的原因是The injectGlobal API was removed and replaced by createGlobalStyle in styled-components v4. 用官方的话来讲,就是这个API 从现在开始废除了,换成 createGlobalStyle 新的API ,作为一个样式组件出现,按照样式组件思想,以一个标签形式被引入。直接像原 injectGlobal 方法一样使用不能生效,要定义一个全局样式变量,这个变量将作为组件插入文档。

  2. 解决措施:

  • 第一步, 用createGlobalStyle定义全局样式,把全局样式包裹在其中,包裹css样式使用反引号字符串,代码如下所示:
import { createGlobalStyle } from 'styled-components'

export const Globalstyle = createGlobalStyle` 
body{
  margin: 0;
  padding: 0
 }`
  • 第二步,在项目主文件导入样式,代码如下所示:
import { Globalstyle } from './style'
  • 第三步,以样式组件的方式当作标签引入,代码如下所示:

class App extends Component {
  render () {
    return (
      <Fragment>
        <GlobalStyled/>
      </Fragment>
    )
  }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值