使用styled-components报错 Attempted import error: injectGlobal is not exported from styled-components

在学习React构建简书网站项目时,遇到styled-components的injectGlobal已废弃的问题。根据官方更新,需使用createGlobalStyle替代。在style.js中使用createGlobalStyle定义全局样式,并在index.js中引入和渲染,成功解决报错并实现全局样式设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用styled-components报错 Attempted import error: injectGlobal is not exported from styled-components

慕课网中用React实现的简书网站的项目学习,7-1项目目录搭建,Styled-Components与Reset.css的结合使用

按照视频流程:

1.先安装styled-components

cnpm add styled-componen

2.然后将css文件改为js文件style.js,并编辑代码:

import { injectGlobal } from 'styled-components'

injectGlobal `
  body{
    margin:0;
    padding:0;
  }
`;

此时运行则会报出标题的错误。

报错原因:

官网链接

在这里插入图片描述

这个injectGlobal已经废除了,已经有新的实现方法了。

解决方案:

在和视频一样安装了styled-components并且把css文件改为js文件style.js,在style.js里面,使用createGlobalStyle方法进行替代并且把它的使用方法也相应改变:

具体代码为:

import { createGlobalStyle } from 'styled-components'

export const GlobalStyled = createGlobalStyle`
    body{
      margin:0;
      padding:0;
      background:green;
    }
`;

还需要index.js中引用并把相应组件添加进来,具体代码如下:

import React from 'react';
import {GlobalStyled} from './style.js';

function App() {
  return (
    <div>
      <GlobalStyled />
      hello world
    </div>
  );
}

export default App;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值