使用styled-components报错Attempted import error: ‘injectGlobal’ is not exported from ‘styled-components’.
一、安装styled-componen
npm add styled-componen
二、使用方法
- 将css文件改为js文件
style.js
,并编辑代码:
import { injectGlobal } from 'styled-components'
injectGlobal `
body{
margin:0;
padding:0;
}
`
2.运行代码报错:Attempted import error: 'injectGlobal' is not exported from 'styled-components'.
三、解决方案:
官网解释:https://styled-components.com/docs/api#primary
意思就是说当前这个方法被废除了,使用createGlobalStyle
方法进行替代:
import { createGlobalStyle } from 'styled-components'
createGlobalStyle `
body{
margin:0;
padding:0;
background:green
}
`
但是!!!这样直接改完之后虽然不报错,但是样式也没有生效,我们需要更改一下它的使用方法:
import { createGlobalStyle } from 'styled-components'
export const GlobalStyled = createGlobalStyle`
body{
margin:0;
padding:0;
background:green;
}
`
组件中引用:
import React from 'react';
import {GlobalStyled} from './style.js';
function App() {
return (
<div className="App">
<GlobalStyled />
</div>
);
}
export default App;
这样就可以生效啦~~