首页 > 解决方案 > 状态改变时在 React JS 中实现过渡效果

问题描述

我在 React 页面上有一张图片。当状态更新为新图像时,我想执行以下过渡效果:

效果应该类似于穿过墙壁进入新场景。

我如何在 React 中做到这一点?

标签: javascriptcssreactjscss-transitions

解决方案


正如@pgsandstrom 提到的,React 过渡组是要走的路。不幸的是,它对开发人员不太友好(学习曲线相当陡峭)。

这是一个工作示例:https ://codesandbox.io/s/6lmv669kz

✔ 原始图像在淡出时放大

✔ 新图像在淡入时放大

过渡示例.js

import random from "lodash/random";
import React, { Component } from "react";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import uuid from "uuid/v1";

const arr = [
  {
    id: uuid(),
    url: `https://loremflickr.com/600/100?lock=${random(0, 999)}`
  },
  {
    id: uuid(),
    url: `https://loremflickr.com/600/100?lock=${random(0, 999)}`
  },
  {
    id: uuid(),
    url: `https://loremflickr.com/600/100?lock=${random(0, 999)}`
  }
];

export default class TransitionExample extends Component {
  state = {
    index: 0,
    selected: arr[0]
  };

  nextImage = () =>
    this.setState(prevState => {
      const newIndex = prevState.index < arr.length - 1 ? prevState.index + 1 : 0;
      return {
        index: newIndex,
        selected: arr[newIndex]
      };
    });

  render = () => (
    <div className="app">
      <div style={{ marginBottom: 30, height: 100 }}>
        <TransitionGroup>
          <CSSTransition
            key={this.state.selected.id}
            timeout={1000}
            classNames="messageout"
          >
            <div style={{ marginTop: 20 }}>
              <img className="centered-image" src={this.state.selected.url} />
            </div>
          </CSSTransition>
        </TransitionGroup>
      </div>
      <div style={{ textAlign: "center" }}>
        <button
          className="uk-button uk-button-primary"
          onClick={this.nextImage}
        >
          Next Image
        </button>
      </div>
    </div>
  );
}

样式.css

.app {
  margin: 0 auto;
  overflow: hidden;
  width: 700px;
  height: 800px;
}

.centered-image {
  display: block;
  margin: 0 auto;
}

/* starting ENTER animation */
.messageout-enter {
  position: absolute;
  top: 0;
  left: calc(13% + 5px);
  right: calc(13% + 5px);
  opacity: 0.01;
  transform: translateY(0%) scale(0.01);
}

/* ending ENTER animation */
.messageout-enter-active {
  opacity: 1;
  transform: translateY(0%) scale(1);
  transition: all 1000ms ease-in-out;
}

/* starting EXIT animation */
.messageout-exit {
  opacity: 1;
  transform: scale(1.01);
}

/* ending EXIT animation */
.messageout-exit-active {
  opacity: 0;
  transform: scale(4);
  transition: all 1000ms ease-in-out;
}

推荐阅读