使用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;