我们先使用npx create-react-app xxx(project name) 来创建项目。
我们删除掉src 目录下,暂时不用的文件,只留下 index.js , index.css, App.js 三个文件。
然后呢,为了实现css 的模块化,使模块间的css 不会冲突,我们使用一个第三方模块Styled-components对css 样式进行管理。
好的,先来下载安装它。
用命令 yarn add styled-components
安装好了后,就可以重启服务了。
然后呢,我们可以重新来引用样式了。首先,我们将index.css 改名为 style.js。然后,在index.js 中引用的地方我们改为 import './style.js'。
然后,我们把style.js 中的内容改为:
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: green;
}
`;
然后在App.js 中引入,如下。
import React, { Component } from 'react';
import { GlobalStyle } from './style.js';
class App extends Component {
render() {
return (
<div>
<GlobalStyle />
<div>
hello world
</div>
</div>
);
}
}
export default App;
然后呢,我们这个项目是一个PC端项目,需要做到,样式在所有浏览器上统一。那么,就需要用到Reset.css 文件了。
我们可以在网上找到它:https://meyerweb.com/eric/tools/css/reset/
然后把它粘贴到我们style.js 的全局样式里覆盖掉之前的全局样式。下面就是style.js 的代码了。
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
`;
Done