首页 > 解决方案 > 如何保存 CSS 动画

问题描述

我目前正在通过 React 和 CSS 制作 toast/snackbar。我打开和关闭了小吃店,但是不知道要添加什么才能让动画保持几秒钟?'fade-in' 属性充当默​​认状态,而 'fade-in-show' 充当动画。

反应JS

 import React, { Component } from 'react';
import './styles.css';

class Toaster extends Component {
  componentDidMount = () => {
    setTimeout(() => this.setState({ fade: true }), 100);
    setTimeout(() => this.setState({ fade: false }), 3000);
  };

  state = {
    fade: false,
  };

  render() {
    const { status, children } = this.props;

    const styles = {
      box: {
        position: 'absolute',
        top: 20,
        right: 0,
        display: 'block',
        background: 'green',
        marginBottom: '1em',
        zIndex: 9999,
      },
      position: {
        position: 'absolute',
        alignItems: 'center',
        top: '18%',
        paddingLeft: '10px',
      },
    };
    if (children) {
      return (
        <div>
          <div
            style={styles.box}
            id={this.state.fade ? 'fade-in-show' : 'fade-in'}
          >
            <div style={styles.position}>{children}</div>
          </div>
        </div>
      );
    }
    return null;
  }
}

export default Toaster;

CSS

#fade-in {
  height: 50px;
  width: 1px;
  opacity: 0;
  transition: all 2.2s ease;
}

#fade-in-show {
  opacity: 1;
  height: 50px;
  width: 500px;
  transition: all 2.2s ease;
}

标签: cssreactjs

解决方案


就 CSS 而言,您可以transition通过在持续时间值之前添加延迟值来延迟属性。这是一个示例,如果您想延迟五秒钟...

transition: all 5s 2.2s ease


推荐阅读