javascript - 状态改变时在 React JS 中实现过渡效果
问题描述
我在 React 页面上有一张图片。当状态更新为新图像时,我想执行以下过渡效果:
- 原始图像应放大和淡出
- 新图像也应该放大和淡入
效果应该类似于穿过墙壁进入新场景。
我如何在 React 中做到这一点?
解决方案
正如@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;
}
推荐阅读
- c - 如何在代码块中用 c 绘制样条曲线?
- python - 如何删除单词末尾的数字?
- c++ - 无法遍历链表,无法弄清楚我的方法有什么问题?
- node.js - Discord(JS)机器人未检测到存在更新
- java - 将一个类编译到不同的文件夹中
- influxdb - InfluxDB - 查询每个现有标签的最后一个值的 MAX
- python - optomax 数字液体传感器 - 树莓派的 python
- java - Remove every space EXCEPT leading spaces
- canvas - 当我有响应的画布宽度和高度时,html5画布的问题无法呈现矩形
- java - 在 SSL SOAP 请求期间: SSLHandshake.consume 忽略 com.sun.jndi.ldap.object.disableendpointidentification 的值