项目目录搭建, styled-components 与 reset.css 的使用

本文介绍如何在React项目中使用Styled-components进行CSS样式的模块化管理,并引入Reset.css确保跨浏览器样式一致性。

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

我们先使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值