在本章中,我们将学习react如何使用动画元素。
这是react插件,用于创建基本的css转换和动画。从命令提示符窗口中安装它 -
f:\worksp\reactjs\reactapp> npm install react-addons-css-transition-group
在项目根目录里面创建一个新的文件夹:css
,并在文件夹中创建一个文件:style.css 。 为了能够在应用程序中使用它,需要将它添加到index.html
中的head
元素中。如下文件(index.html)代码所示 -
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>react动画示例</title>
<link rel = "stylesheet" type = "text/css" href = "css/style.css">
</head>
<body>
<div id = "app"></div>
<script type = "text/javascript" src = "index.js"></script>
</body>
</html>
创建一个基本的react组件。 reactcsstransitiongroup
元素将被用作想要动画的组件的包装。它将使用transitionappear
和transitionappeartimeout
,而transitionenter
和transitionleave
是false
。
文件:app.jsx -
import react from 'react';
var reactcsstransitiongroup = require('react-addons-css-transition-group');
class app extends react.component {
render() {
return (
<div>
<reactcsstransitiongroup transitionname = "example"
transitionappear = {true} transitionappeartimeout = {500}
transitionenter = {false} transitionleave = {false}>
<h1>my element...</h1>
</reactcsstransitiongroup>
</div>
);
}
}
export default app;
文件:main.js -
import react from 'react'
import reactdom from 'react-dom';
import app from './app.jsx';
reactdom.render(<app />, document.getelementbyid('app'));
css动画非常简单。文件:css/style.css -
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
当启动应用程序,元素将淡入。
当想要添加或删除列表中的元素时,可以使用输入和离开动画。
文件:app.jsx -
import react from 'react';
var reactcsstransitiongroup = require('react-addons-css-transition-group');
class app extends react.component {
constructor(props) {
super(props);
this.state = {
items: ['item 1...', 'item 2...', 'item 3...', 'item 4...']
}
this.handleadd = this.handleadd.bind(this);
};
handleadd() {
var newitems = this.state.items.concat([prompt('create new item')]);
this.setstate({items: newitems});
}
handleremove(i) {
var newitems = this.state.items.slice();
newitems.splice(i, 1);
this.setstate({items: newitems});
}
render() {
var items = this.state.items.map(function(item, i) {
return (
<div key = {item} onclick = {this.handleremove.bind(this, i)}>
{item}
</div>
);
}.bind(this));
return (
<div>
<button onclick = {this.handleadd}>add item</button>
<reactcsstransitiongroup transitionname = "example"
transitionentertimeout = {500} transitionleavetimeout = {500}>
{items}
</reactcsstransitiongroup>
</div>
);
}
}
export default app;
文件:main.js -
import react from 'react'
import reactdom from 'react-dom';
import app from './app.jsx';
reactdom.render(<app />, document.getelementbyid('app'));
文件:css/style.css -
.example-enter {
opacity: 0.01;
}
.example-enter.example-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.example-leave {
opacity: 1;
}
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity 500ms ease-in;
}
当启动应用程序,然后点击添加项目按钮,会出现提示。
当点击"add item..."
并输入名称,然后按确定,新的元素将淡入。
现在可以通过点击删除一些项目(例如:item 3 … )。 该项目将从列表中淡出。