React项目中使用styled-components以及css有关技巧

152 阅读1分钟

Styled-components 是目前 React 样式方案中最受关注的一种,它既具备了 css-in-js 的模块化与参数化优点,又完全使用CSS的书写习惯,不会引起额外的学习成本。

使用styled-components

安装

安装styled-componentstypescript依赖,分别运行以下代码:

yarn add styled-components

yarn add --dev @types/styled-components

参考文档

在使用时需要先引入:

import styled from "styled-components";

使用示例:

const Item = styled.div` 
  display: flex; justify-content: space-between; 
  background: #fff; 
  font-size: 18px; 
  line-height: 20px; 
  padding: 10px 16px; 
` 
function Item(){
  return( <Item> hello world </Item> ) 
 }

CSS相关设置

支持SCSS: SCSS相对于CSS语法来说,改动较小,但是更加便捷,更易于理解,开发效率高。因此建议使用SCSS语法来编写样式。

建议不用node-sass,因为下载慢,本地编译也慢,易出现安装失败的情况。用dart-sass更好。create-react-app不支持dart-sass,引入时需要‘狸猫换太子’:

方法:yarn add node-sass@npm:dart-sass。此时引入的就是dart-sass

image.png

引入css-normalize

为了让不同浏览器下css样式趋于一致,引入css-normalize,方法:在index.css文件内加上@import-normalize;

中文字体设置

可以参考Fonts.css网站的css。直接复制引用,或者在helper.scss文件内,用

$font-xxx:字体内容

再在其他位置引用$font-xxx.

其他tips

阴影:一个比较好用的css阴影:box-shadow: 0 0 3px rgba(0,0,0,0.25);可以根据需要更改参数。
加不占体积的元素:用伪元素。示例:

::after{
  content:'';//内容记得置空
  background: #333;
  display: block;
  height:3px;
  position: absolute;//决定定位的父元素需要加上position:reletive;
  width: 100%;//绝对定位之后宽度被置为0,需要再写一下
  bottom:0;left:0;//定位写两个,避免在某些情况下出现bug。
}