React学习笔记三(CSS方案)

1. 过渡动画实现

1.1 react-transition-group

在开发中,我们想要给一个组件的显示和消失添加某种过渡动画,可以很好的增加用户体验。

当然,我们可以通过原生的CSS来实现这些过渡动画,但是React社区为我们提供了 react-transition-group 用来完成过渡动画。

这个库可以帮助我们方便的实现组件的 入场 和 离场 动画,使用时需要进行额外的安装:

npm install react-transition-group --save 

react-transition-group 本身非常小,不会为我们应用程序增加过多的负担。

1.2 主要组件

react-transition-group 主要包含四个组件:

1、Transition

  • 该组件是一个和平台无关的组件(不一定要结合CSS);
  • 在前端开发中,我们一般是结合CSS来完成样式,所以比较常用的是CSSTransition;

2、CSSTransition

  • 在前端开发中,通常使用 CSSTransition 来完成过渡动画效果

3、SwitchTransition

  • 两个组件显示和隐藏切换时,使用该组件

4、TransitionGroup

  • 将多个动画组件包裹在其中,一般用于列表中元素的动画;

1.3 CSSTransition

CSSTransition 是基于 Transition组件构建的:

CSSTransition 执行过程中,有三个状态appear、enter、exit

它们有三种状态,需要定义对应的CSS样式:

  • 第一类,开始状态:对于的类是-appear、-enter、exit;
  • 第二类:执行动画:对应的类是-appear-active、-enter-active、-exit-active;
  • 第三类:执行结束:对应的类是-appear-done、-enter-done、-exit-done;

1.3.1 CSSTransition常见属性

1、in:触发进入或者退出状态

  • 如果添加了unmountOnExit={true},那么该组件会在执行退出动画结束后被移除掉
  • 当 in 为 true 时,触发进入状态,会添加-enter、-enter-acitve的class开始执行动画,当动画执行结束后,会移除两个class,并且添加-enter-done 的 class;
  • 当 in 为 false 时,触发退出状态,会添加-exit、-exit-active的class开始执行动画,当动画执行结束后,会移除两个class,并且添加 -enter-done 的 class;

2、classNames:动画class的名称

  • 决定了在编写css时,对应的class名称:比如card-enter、card-enter-active、card-enter-done;

3、timeout:过渡动画的时间


4、appear:是否在初次进入添加动画(需要和 in 同时为 true)


5、unmountOnExit:退出后卸载组件

其他属性可以参考官网来学习:https://reactcommunity.org/react-transition-group/transition


CSSTransition对应的钩子函数:主要为了检测动画的执行过程,来完成一些 JavaScript 的操作

  • onEnter:在进入动画之前被触发;
  • onEntering:在应用进入动画时被触发;
  • onEntered:在应用进入动画结束后被触发;

【示例:给 App组件中的 h2 添加动画】

在 App.jsx 文件中,先从 react-transition-group 库中引入 CSSTransition ,用它包裹需要添加动画的元素/组件

import React, { PureComponent } from 'react'
import { CSSTransition } from 'react-transition-group'
// 引入 css
import './style.css'
export default class App extends PureComponent {
  constructor() {
    super()
    this.state = { isShow:true }
  }
  render() {
    const {isShow} = this.state
    return (
      <div>
        <button onClick={(e) => this.setState({ isShow: !isShow })}>切换</button>
        <CSSTransition in={isShow} unmountOnExit={true } classNames="foo"
          timeout={2000} appear onEnter={(e) => console.log("开始进入动画")}
          onEntering={(e) => console.log("执行进入动画")}
          // onExited onExit onExiting onExited 略
        >
          <h2>hello</h2>
        </CSSTransition>
      </div>
    );
  }
}

在 style.css 文件中,书写样式

/* 第一次出现的时候的动画 */
.foo-appear{ transform: translateX(-150px) }
.foo-appear-active{
  transform: translateX(0);
  transition: transform 2s ease;
}
/* 进入动画 */
.foo-enter{ opacity: 0 }
.foo-enter-active{ opacity: 1; transition: opacity 2s ease }
/* 离开动画 */
.foo-exit{ opacity: 1 }
.foo-exit-active{
  opacity: 0;
  transition: opacity 2s ease;
}

如果添加动画的组件处于严格模式,可能会报警告如: findDOMNode is deprecated in StrictMode.
方式一:关闭严格模式;
方式二:给需要动画的根元素上绑定 ref ,并在 CSSTransiton 的 nodeRef 属性上 传入即可;

1.4 SwitchTransition

SwitchTransition 可以完成两个组件之间切换的炫酷动画:

  • 比如我们有一个按钮需要在on和off之间切换,我们希望看到on先从左侧退出,off再从右侧进入;
  • 这个动画在vue中被称之为 vue transition modes;
  • react-transition-group 中使用 SwitchTransition 来实现该动画;

SwitchTransition 中主要有一个属性:mode,有两个值

  • in-out:表示新组件先进入,旧组件再移除;
  • out-in:表示新组件先移除,新组建再进入(常用);

如何使用SwitchTransition

  • SwitchTransition组件里面要有 CSSTransition 或者 Transition 组件,不能直接包裹你想要切换的组件;
  • SwitchTransition里面的CSSTransition或Transition组件不再像以前那样接受in属性来判断元素是何种状态,取而代之的是 key属性

【示例】
在 App.jsx 文件中,代码如下

import React, { PureComponent } from 'react'
import { SwitchTransition, CSSTransition } from 'react-transition-group'
import './style.css'
export default class App extends PureComponent {
  constructor() {
    super()
    this.state = {isLogin:true}
  }
  render() {
    const {isLogin}= this.state
    return (
      <div>
        <SwitchTransition mode="out-in">
          {/* 这里要给  CSSTransition 添加key属性,两种状态 key不同即可*/}
          <CSSTransition key={isLogin ? "exit" : "login"} classNames="login" timeout={1000} >
            <div>
              {isLogin ? <h2>退出</h2> : <h3>登录</h3>}
              <button onClick={(e) => this.setState({ isLogin: !isLogin })}>
                {isLogin ? "退出" : "登录"}
              </button>
            </div>
          </CSSTransition>
        </SwitchTransition>
      </div>
    );
  }
}

在 style.css 文件中,代码如下

.login-enter{
  transform: translateX(100px);
  opacity: 0;
}
.login-enter-active{
  transform: translateX(0);
  opacity: 1;
  transition: all 1s ease;
}
.login-exit{
  transform: translateX(0);
  opacity: 1;
}
.login-exit-active{
  transform: translateX(-100px);
  opacity: 0;
  transition: all 1s ease;
}

1.5 TransitionGroup

当我们有一组动画时,需要将这些 CSSTransition 放入到一个TransitionGroup 中来完成动画:

【示例】
在 App.jsx 文件中,用 TransitionGroup 包裹 待渲染列表,列表同时被 CSSTransition 包裹,以添加过渡动效

import React, { PureComponent } from 'react'
import { TransitionGroup, CSSTransition } from "react-transition-group";
import './style.css'
export default class App extends PureComponent {
  constructor() {
    super()
    this.state = {
      books: [
        {id:1,name:'html高级',price:99},
        {id:2,name:'css高级',price:88},
        {id:3,name:'js高级',price:77}
      ]
    }
  }
  addBook() {
    const newBook = {id:new Date().getTime(), name: 'react高级', price: 99 };
    const books = [...this.state.books,newBook];
    this.setState({
      books
    })
  }
  render() {
    const { books } = this.state
    return (
      <div>
        {/* TransitionGroup 默认会被渲染为div ,可通过 component 属性指定 元素 */}
        <TransitionGroup component="ul">
          {books.map((item, index) => (
            <CSSTransition key={item.id} classNames="add" timeout={1000}>
              <li key={index}>{item.name}-{item.price}</li>
            </CSSTransition>
          ))}
        </TransitionGroup>
        <button onClick={(e) => this.addBook()}>添加</button>
      </div>
    );
  }
}

在 style.css 文件中,添加样式

.add-enter{
  transform: translateX(100px);
  opacity: 0;
}
.add-enter-active{
 transform: translateX(0);
 opacity: 1;
 transition: transform 1s ease;
}

2. React 中的 CSS

2.1 组件化天下的CSS

整个前端已经是盛行组件化开发:

  • 而CSS 的设计就不是为组件化而生的,所以在目前组件化的框架中都在需要一种合适的CSS解决方案。

在组件化中选择合适的CSS解决方案应该符合以下条件:

  • 可以编写局部css:css具备自己的作用域,不会随意污染其他组件内的元素;
  • 可以编写动态的css:可以获取当前组件的一些状态,根据状态的变化生成不同的css样式;
  • 支持所有的css特性:伪类、动画、媒体查询等;
  • 编写起来简洁方便、最好符合一贯的css风格特点…等

2.2 React中的CSS

事实上,css一直是 React 的痛点,也是被很多开发者吐槽、诟病的一个点。

在这一点上,Vue做的要好:

  • Vue通过在 .vue 文件中编写 <style><style> 标签来编写自己的样式;
  • 通过是否添加 scoped 属性来决定编写的样式是全局有效还是局部有效;
  • 通过 lang 属性来设置你喜欢的 less、sass等预处理器;
  • 通过内联样式风格的方式来根据最新状态设置和改变css等等…;

Vue在CSS上虽然不能称之为完美,但是已经足够简洁、自然、方便了,至少统一的样式风格不会出现多个开发人员、多个项目采用不一样的样式风格。

相比而言,React官方并没有给出在 React 中统一的样式风格:

  • 由此,从普通的css,到css modules,再到css in js,有几十种不同的解决方案,上百个不同的库;
  • 大家一致在寻找最好的或者说最适合自己的CSS方案,但是到目前为止也没有统一的方案;

2.3 内联样式

内联样式是官方推荐的一种css样式的写法:

  • style 接受一个采用小驼峰命名属性的 JavaScript 对象,而不是 CSS 字符串;
  • 并且可以引用 state 中的状态来设置相关的样式;

【内联样式示例】

import React, { PureComponent } from 'react'
export default class App extends PureComponent {
  constructor() {
    super()
    this.state = {size:20}
  }
  render() {
    const { size } = this.state;
    return (
      <div>
        <button onClick={e=> this.setState({size:size + 2})}>增大文字</button>
        <h2 style={{fontSize:`${size}px`,color:'red'}}>hello</h2>
      </div>
    )
  }
}

内联样式的优点:

  • 内联样式, 样式之间不会有冲突
  • 可以动态获取当前state中的状态

内联样式的缺点:

  • 写法上都需要使用驼峰标识
  • 某些样式没有提示
  • 大量的样式, 代码混乱
  • 某些样式无法编写(比如伪类/伪元素)

2.4 普通的css

普通的css我们通常会编写到一个单独的文件,之后再进行引入。这样的编写方式和普通的网页开发中编写方式是一致的:

  • 如果我们按照普通的网页标准去编写,那么也不会有太大的问题;
  • 但是组件化开发中我们总是希望组件是一个独立的模块,即便是样式也只是在自己内部生效,不会相互影响;
  • 但是普通的css都属于全局的css样式之间会相互影响

这种编写方式最大的问题是样式之间会相互层叠掉;

【普通CSS示例】

import React, { PureComponent } from 'react'
// 使用 import 引入 普通的css文件
import './App.css'
export default class App extends PureComponent {
  render() {
    return (
      <div>
        <h2 className='title'>hello</h2>
        <p className='text'>react</p>
      </div>
    )
  }
}

2.5 css modules

2.5.1 认识 css modules

css modules 并不是React特有的解决方案,而是所有使用了类似于webpack 配置的环境下都可以使用的。

  • 如果在其他项目中使用它,那么我们需要自己来进行配置,比如配置webpack.config.js 中的 modules: true 等。

React 的脚手架已经内置了 css modules 的配置:

  • 只要将 .css/.less/.scss 等样式文件都需要修改成.module.css/.module.less/.module.scss 等即可

css modules确实解决了局部作用域的问题,也是很多人喜欢在React中使用的一种方案,但是这种方案也有自己的缺陷:

  • 引用的类名,不能使用连接符(.home-title),在JavaScript中是不识别的;
  • 所有的className都必须使用{style.className} 的形式来编写;
  • 不方便动态来修改某些样式,依然需要使用内联样式的方式;

如果你觉得上面的缺陷可以接收,那么你在开发中完全可以选择使用css modules来编写,并且也是在React中很受欢迎的一种方式。

【示例】

// App.module.css 文件
.title{
  font-size: 30px;
  color: red;
}
.text{
  color: skyblue;
}
// App.jsx 文件
import React, { PureComponent } from 'react'
import AppStyle from "./App.module.css"
export default class App extends PureComponent {
  render() {
    return (
      <div>
        <h2 className={AppStyle.title}>hello</h2>
        <p className={ AppStyle.text}>react</p>
      </div>
    );
  }
}

2.5.1 使用 less

使用工具 craco 来 配置 webpack;

步骤一: 下载 craco

npm i -D @craco/craco

在这里插入图片描述
步骤二:下载 craco-less 因为 CRA 为 5.0.1 版本,比较新,所以要安装 craco-less@alpha版本

npm i -S craco-less@alpha

步骤三:在 根目录创建 craco.config.js 文件,添加如下代码

const CracoLessPlugin = require("craco-less");
module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: { "@primary-color": "#1DA57A" },
            javascriptEnabled: true,
          },
        },
      },
    },
  ],
};

步骤四:在 package.json 文件中,不能用原来的指令来启动项目,要通过 craco 的 指令启动

- 号为原来的,替换为 + 号后面的

"scripts": {
-  "start": "react-scripts start"
+  "start": "craco start"
-  "build": "react-scripts build"
+  "build": "craco build"
-  "test": "react-scripts test"
+  "test": "craco test"
}

最后重启项目即可

2.6 CSS in JS

官方文档也有提到过CSS in JS这种方案:

  • “CSS-in-JS” 是指一种模式,其中 CSS 由 JavaScript 生成而不是在外部文件中定义;
  • 注意此功能并不是 React 的一部分,而是由第三方库提供;
  • React 对样式如何定义并没有明确态度;

在传统的前端开发中,我们通常会将结构(HTML)、样式(CSS)、逻辑(JavaScript)进行分离。

  • 但是在前面的学习中,React的思想中认为逻辑本身和UI是无法分离的,所以才会有了JSX的语法。
  • 样式呢?样式也是属于UI的一部分;
  • 事实上CSS-in-JS的模式就是一种将样式(CSS)也写入到JavaScript中的方式,并且可以方便的使用JavaScript的状态;
  • 所以 React 有被人称之为 All in JS;

2.6.1 styled-components

很多优秀的 CSS-in-JS 的库非常强大、方便:

  • CSS-in-JS通过JavaScript来为CSS赋予一些能力,包括类似于CSS预处理器一样的样式嵌套、函数定义、逻辑复用、动态修改状态等等;
  • 虽然CSS预处理器也具备某些能力,但是获取动态状态依然是一个不好处理的点;
  • 所以,目前可以说CSS-in-JS是React编写CSS最为受欢迎的一种解决方案;

目前比较流行的 CSS-in-JS 的库有哪些呢?

  • styled-components
  • emotion
  • glamorous

目前可以说 styled-components 依然是社区最流行的CSS-in-JS库

2.6.2 styled的基本使用

vscode 推荐插件 vscode-styled-components;提供了css代码提示

安装 styled-components 包

npm install styled-components

styled-components的本质是通过函数的调用,最终创建出一个组件:

  • 这个组件会被自动添加上一个不重复的class;
  • styled-components会给该class添加相关的样式;

另外,它支持类似于CSS预处理器一样的样式嵌套:

  • 支持直接子代选择器或后代选择器,并且直接编写样式;
  • 可以通过&符号获取当前元素;
  • 直接伪类选择器、伪元素等;

【示例】
在 App.jsx 中代码如下,AppWraper 为 通过 styled 创建的一个 组件

import React, { PureComponent } from 'react'
import { AppWraper } from './style';
export default class App extends PureComponent {
  render() {
    return (
      <AppWraper>
        <div className='section'>
          <h2 className='title'>我是标题</h2>
          <p className='content'>我是内容</p>
        </div>
        <div className='footer'>hhhh</div>
      </AppWraper>
    );
  }
}

在 style.js 代码如下;通过 styled-components 的 styled ,创建一个 div;它返回一个组件,该组件具有 ``模板字符串中的样式;

import styled from "styled-components";
// 注意,这里用到了 标签模板字符串;
export const AppWraper = styled.div`
  .section {
    border: 1px solid red;
    .title{
      font-size: 30px;
      color: skyblue;
      &:hover{
        background-color: purple;
      }
    }
  }
  .footer {
    border: 1px solid orange;
  }
`;

2.6.3 接收外部的props

props 可以被传递给 styled 组件

  • 获取props需要通过 ${} 传入一个插值函数,props会作为该函数的参数;
  • 这种方式可以有效的解决动态样式的问题;

在 App.jsx 中,给 样式组件 AppWraper 传入 props

import React, { PureComponent } from 'react'
import { AppWraper } from './style';
export default class App extends PureComponent {
  constructor() {
    super()
    this.state = {
      color: 'red',
      height:20
    }
  }
  render() {
    const {color,height} = this.state
    return (
      <AppWraper color={color} height={ height }>
        <input type="text" />
      </AppWraper>
    );
  }
}

在 style.js 中,接收 props,接收的方式是 在模板字符串占位符中,传入一个函数,返回需要使用的 props 属性

import styled from "styled-components";
export const AppWraper = styled.div`
  input{
    /* 在占位符中 传入函数 */
    height: ${props => props.height}px;
    border: 2px solid ${props  => props.color};
  }
`;

2.6.4 通过 attrs 定义 属性

1、定义元素的默认属性

export const MyInput = styled.input.attrs({
  placeholder: "请输入密码",
  type: "password",
})`
  border-color: red;
  &:focus {
    outline-color: orange;
  }
`;

2、使用 传入的 props 属性,如果没有,则使用 默认属性

export const MyInput = styled.input.attrs((props) => {
  return {
    myColor: props.color || "red",
    myHeight: props.height || "10px",
  };
})`
  color:${(props) => props.myColor};
  height:${(props) => props.myHeight};
`;

2.6.5 styled高级特性

一:支持样式继承

// 在 style.js 文件
import styled from "styled-components";
export const MyButton = styled.button`
  padding: 8px 30px;
  border-radius: 5px;
`
export const MyWarnButton = styled(MyButton)`
  background-color: red;
  color: #fff;
`
// 在 App.jsx 文件
import React, { PureComponent } from 'react'
import { MyButton, MyWarnButton } from "./style";
export default class App extends PureComponent {
  render() {
    return (
      <div>
        <MyButton>点击</MyButton>
        <MyWarnButton>点击</MyWarnButton>
      </div>
    );
  }
}

二:styled 设置主题;给后代子元素传递数据

【示例】

1:首先引入 ThemeProvider,给后代 Home组件 提供 数据

// App.jsx 
import React, { PureComponent } from 'react'
import { ThemeProvider } from 'styled-components';
import Home from "./Home"
export default class App extends PureComponent {
  render() {
    return (
      <div>
        <ThemeProvider theme={{ color: 'red', fontSize: '30px' }}>
          <Home></Home>
        </ThemeProvider>
      </div>
    );
  }
}

2:在 Home/index.jsx 定义 Home 组件,Home 组件 被 HomeWrapper 样式组件包裹

// Home -> index.jsx
import React, { PureComponent } from 'react'
import {HomeWrapper} from "./style"
export default class index extends PureComponent {
  render() {
    return (
      <HomeWrapper>
        <div className='top'>yyy</div>
        <div className='bottom'>xxx</div>
      </HomeWrapper>
    )
  }
}

3:在 Home/style.js 中定义 Home 的样式组件 HomeWrapper,并接收和使用了 ThemeProvider 提供的数据

import styled from "styled-components";
export const HomeWrapper = styled.div`
  .top {
    background-color: purple;
    color: ${(props) => props.theme.color};
  }
  .bottom {
    background-color: skyblue;
    font-size: ${(props) => props.theme.fontSize};
  }
`;

2.6.6 React中添加class

React在JSX给了我们开发者足够多的灵活性,你可以像编写JavaScript 代码一样,通过一些逻辑来决定是否添加某些class

<div>
  <h2 className={`title ${isActive ? 'active':''}`}>标题</h2>
  <h2 className={['title',(isActive ? 'active': '')].join(' ')}>标题</h2>
</div>

但是如果动态添加的类比较多的时候,这种写法就会比较繁琐,冗余

这时可以借助于一个第三方的库:classnames ,用于便捷地动态添加类

官方地址 https://github.com/JedWatson/classnames

下载

npm install classnames

使用方式(其实和vue使用动态 class 很相似)

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
classNames("a", ["b", { c: true }])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值