在 react.js 框架中使用 transition 过渡动画

实现一个 div 标签首次加载时的过渡动画,效果为:高度从 0px 缓缓增加到 100px,过渡动画时长 1s。

实现思路

首先在 state 中储存一个默认的 style 样式,也就是过渡动画的起始值,再将 div 的 style 属性的值设置为该 state 中的样式。

使用 useEffect() 监听事件 “当组件被插入 DOM 树”,此事件可以理解为class 组件中的componentDidMount ,在此事件的回调函数中更新 state ,当此事件触发时 state 会被更新,组件发生渲染, div 的样式随之被改变,过渡动画就产生了。

ps:使用 setTimeout() 是为了防止 componentDidMount 中的 setState() 阻塞浏览器界面渲染。

示例代码

import React, { useState, useEffect } from 'react';

function App() {
  console.log('App render');
  
  //设置默认样式,并添加transition属性
  const [styles, setStyleSheet] = useState({
    height: '0px',
    width: '50px',
    backgroundColor: 'blue',
    transition: 'all 1s',
  });

  //相当于class组件中的componentDidMount
  useEffect(() => {

    //添加延迟,以免过快导致动画失效
    setTimeout(() => {
      setStyleSheet({ ...styles, height: '100px' });
    }, 100);
  }, []);

  return (
    <>
      <div style={styles}></div>
    </>
  );
}

export default App;

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注