以前一直投入在
React Native中,寫動(dòng)畫的時(shí)候不是用CSS 中的 transitions / animations,就是依賴像GreenSock這樣的庫(kù),最近轉(zhuǎn)向Web,在Tweet得到很多大佬關(guān)于React Web 動(dòng)畫的回應(yīng),于是決定分享給大家,如有其他見解,非常歡迎在下面評(píng)論中交流
以下便是本文要分享的創(chuàng)建 React 動(dòng)畫 的幾種方式
- CSS animation
- JS Style
- React Motion
- Animated
- Velocity React
下面,勒次個(gè)特斯大特一特
CSS animation
給元素添加 class 是最簡(jiǎn)單,最常見的書寫方式。如果你的 app 正在使用 CSS,那么這將是你最愉快的選擇
贊同者: 我們只需修改 opacity 和 transform 這樣的屬性,就可構(gòu)建基本的動(dòng)畫,而且,在組件中,我們可以非常容易地通過 state 去更新這些值
反對(duì)者:這種方式并不跨平臺(tái),在 React Native 中就不適用,而且,對(duì)于較復(fù)雜的動(dòng)畫,這種方式難以控制
接下來,我們通過一個(gè)實(shí)例來體驗(yàn)一下這種創(chuàng)建方式:當(dāng) input focus 的時(shí)候,我們?cè)黾铀膶挾?/code>
首先,我們要?jiǎng)?chuàng)建兩個(gè) input 要用到的 class
.input {
width: 150px;
padding: 10px;
font-size: 20px;
border: none;
border-radius: 4px;
background-color: #dddddd;
transition: width .35s linear;
outline: none;
}
.input-focused {
width: 240px;
}
一個(gè)是它原始的樣式,一個(gè)是它 focus 后的樣式
下面,我們就開始書寫我們的 React 組件
在此,推薦一個(gè) 在線的 React VS Code IDE,真的很強(qiáng)大,讀者不想構(gòu)建自己的 React app,可以在其中檢驗(yàn)以下代碼的正確性

class App extends Component {
state = {
focused: false,
}
componentDidMount() {
this._input.addEventListener('focus', this.focus);
this._input.addEventListener('blur', this.focus);
}
focus = () => {
this.setState(prevState => ({
focused: !prevState.focused,
}));
}
render() {
return (
<div className="App">
<div className="container">
<input
ref={input => this._input = input}
className={['input', this.state.focused && 'input-focused'].join(' ')}
/>
</div>
</div>
);
}
}
- 我們有一個(gè)
focused的state,初始值為false,我們通過更新該值來創(chuàng)建我們的動(dòng)畫 - 在
componentDidMount中,我們添加兩個(gè)監(jiān)聽器,一個(gè)focus,一個(gè)blur,指定的回調(diào)函數(shù)都是focus -
focus方法會(huì)獲取之前focused的值,并負(fù)責(zé)切換該值 - 在
render中,我們通過state來改變input的classNames,從而實(shí)現(xiàn)我們的動(dòng)畫
JS Style
JavaScipt styles 跟 CSS 中的 classes 類似,在 JS 文件中,我們就可以擁有所有邏輯
贊同者:跟 CSS 動(dòng)畫 一樣,且它的表現(xiàn)更加清晰。它也不失為一個(gè)好方法,可以不必依賴任何 CSS
反對(duì)者:跟 CSS 動(dòng)畫 一樣,也是不跨平臺(tái)的,且動(dòng)畫一旦復(fù)雜,也難以控制
在下面的實(shí)例中,我們將創(chuàng)建一個(gè) input,當(dāng)用戶輸入時(shí),我們將一個(gè) button 從 disable 轉(zhuǎn)變?yōu)?enable

class App extends Component {
state = {
disabled: true,
}
onChange = (e) => {
const length = e.target.value.length;
if (length > 0) {
this.setState({ disabled: false });
} else {
this.setState({ disabled: true });
}
}
render() {
const { disabled } = this.state;
const label = disabled ? 'Disabled' : 'Submit';
return (
<div style={styles.App}>
<input
style={styles.input}
onChange={this.onChange}
/>
<button
style={Object.assign({},
styles.button,
!this.state.disabled && styles.buttonEnabled
)}
disabled={disabled}
>
{label}
</button>
</div>
);
}
}
const styles = {
App: {
display: 'flex',
justifyContent: 'left',
},
input: {
marginRight: 10,
padding: 10,
width: 190,
fontSize: 20,
border: 'none',
backgroundColor: '#ddd',
outline: 'none',
},
button: {
width: 90,
height: 43,
fontSize: 17,
border: 'none',
borderRadius: 4,
transition: '.25s all',
cursor: 'pointer',
},
buttonEnabled: {
width: 120,
backgroundColor: '#ffc107',
}
}
- 我們有一個(gè)
disabled的state,初始值為true -
onChange方法會(huì)獲取用戶的輸入,當(dāng)輸入非空時(shí),就切換disabled的值 - 根據(jù)
disabled的值,確定是否將buttonEnabled添加到button中
React Motion
React Motion 是 Cheng Lou 書寫的一個(gè)非常不錯(cuò)的開源項(xiàng)目。它的思想是你可以對(duì)Motion 組件 進(jìn)行簡(jiǎn)單的樣式設(shè)置,然后你就可以在回調(diào)函數(shù)中通過這些值,享受動(dòng)畫帶來的樂趣
對(duì)于絕大多數(shù)的動(dòng)畫組件,我們往往不希望對(duì)動(dòng)畫屬性(寬高、顏色等)的變化時(shí)間做硬編碼處理,react-motion 提供的 spring 函數(shù)就是用來解決這一需求的,它可以逼真地模仿真實(shí)的物理效果,也就是我們常見的各類緩動(dòng)效果
下面是一個(gè)森破的示例
<Motion style={{ x: spring(this.state.x) }}>
{
({ x }) =>
<div style={{ transform: `translateX(${x}px)` }} />
}
</Motion>
這是官方提供的幾個(gè) demo,真的可以是不看不知道,一看嚇一跳
贊同者:React Motion 可以在 React Web 中使用,也可以在 React Native 中使用,因?yàn)樗强缙脚_(tái)的。其中的 spring 概念最開始對(duì)我來說感覺挺陌生,然而上手之后,發(fā)現(xiàn)它真的很神奇,并且,它有很詳細(xì)的 API
反對(duì)者:在某些情況下,他不如純 CSS / JS 動(dòng)畫,雖然它有不錯(cuò)的 API,容易上手,但也需要學(xué)習(xí)成本
為了使用它,首先我們要用 yarn 或 npm 安裝它
yarn add react-motion
在下面的實(shí)例中,我們將創(chuàng)建一個(gè) dropdown 菜單,當(dāng)點(diǎn)擊按鈕時(shí),下拉菜單友好展開

class App extends Component {
state = {
height: 38,
}
animate = () => {
this.setState((state) => ({ height: state.height === 233 ? 38 : 233 }));
}
render() {
return (
<div className="App">
<div style={styles.button} onClick={this.animate}>Animate</div>
<Motion
style={{ height: spring(this.state.height) }}
>
{
({ height }) =>
<div style={Object.assign({}, styles.menu, { height } )}>
<p style={styles.selection}>Selection 1</p>
<p style={styles.selection}>Selection 2</p>
<p style={styles.selection}>Selection 3</p>
<p style={styles.selection}>Selection 4</p>
<p style={styles.selection}>Selection 5</p>
<p style={styles.selection}>Selection 6</p>
</div>
}
</Motion>
</div>
);
}
}
const styles = {
menu: {
marginTop: 20,
width: 300,
border: '2px solid #ddd',
overflow: 'hidden',
},
button: {
display: 'flex',
width: 200,
height: 45,
justifyContent: 'center',
alignItems: 'center',
border: 'none',
borderRadius: 4,
backgroundColor: '#ffc107',
cursor: 'pointer',
},
selection: {
margin: 0,
padding: 10,
borderBottom: '1px solid #ededed',
},
}
- 我們從
react-motion中 importMotion和spring - 我們有一個(gè)
height的state,初始值為38,代表menu的高度 -
animate方法設(shè)置menu的height,如果原 height為38,則設(shè)置新 height為233,如果原 height為233,則設(shè)置新 height為38 - 在
render中,我們使用Motion 組件包裝整個(gè)p 標(biāo)簽列表,將this.state.height的當(dāng)前值設(shè)為組件的height,然后在組件的回調(diào)函數(shù)中使用該值作為整個(gè)下拉的高度 - 當(dāng)按鈕被點(diǎn)擊時(shí),我們通過
this.animate切換下拉的高度
Animated
Animated 是基于 React Native 使用的同一個(gè)動(dòng)畫庫(kù)建立起來的
它背后的思想是創(chuàng)建聲明式動(dòng)畫,通過傳遞配置對(duì)象來控制動(dòng)畫
贊同者:跨平臺(tái),它在 React Native 中已經(jīng)非常穩(wěn)定,如果你在 React Native 中使用過,那么你將不用再重復(fù)學(xué)習(xí)。其中的 interpolate 是一個(gè)神奇的插值函數(shù),我們將在下面看到
反對(duì)者:基于 Twitter 的交流,它目前貌似不是 100% 的穩(wěn)定,在老的瀏覽器中的,存在前綴和性能的問題,而且,它也有學(xué)習(xí)成本
為了使用 Animated,我們首先還是要用 yarn 或 npm 安裝它
yarn add animated
在下面的實(shí)例中,我們將模擬在提交表單成功后顯示的動(dòng)畫 message

import Animated from 'animated/lib/targets/react-dom';
import Easing from 'animated/lib/Easing';
class AnimatedApp extends Component {
animatedValue = new Animated.Value(0);
animate = () => {
this.animatedValue.setValue(0);
Animated.timing(
this.animatedValue,
{
toValue: 1,
duration: 1000,
easing: Easing.elastic(1),
}
).start();
}
render() {
const marginLeft = this.animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [-120, 0],
});
return (
<div className="App">
<div style={styles.button} onClick={this.animate}>Animate</div>
<Animated.div
style={
Object.assign(
{},
styles.box,
{ opacity: this.animatedValue, marginLeft })}
>
<p>Thanks for your submission!</p>
</Animated.div>
</div>- 我們將 `animatedValue`
和 `marginLeft` 作為 `Animated.div ` 的 `style` 屬性, );
}
}
const styles = {
button: {
display: 'flex',
width: 125,
height: 50,
justifyContent: 'center',
alignItems: 'center',
border: 'none',
borderRadius: 4,
backgroundColor: '#ffc107',
cursor: 'pointer',
},
box: {
display: 'inline-block',
marginTop: 10,
padding: '0.6rem 2rem',
fontSize:'0.8rem',
border: '1px #eee solid',
borderRadius: 4,
boxShadow: '0 2px 8px rgba(0,0,0,.2)',
},
}
- 從
animated中 importAnimated和Easing - 用
new Animated.Value(0)創(chuàng)建一個(gè)值為0的類屬性 -animatedValue - 創(chuàng)建
animate方法,處理所有的動(dòng)畫,首先通過this.animatedValue.setValue(0)初始化動(dòng)畫值,實(shí)現(xiàn)的效果就是每次重新執(zhí)行該動(dòng)畫,然后調(diào)用Animated.timing,animatedValue作為第一個(gè)參數(shù)傳遞,配置對(duì)象作為第二個(gè)參數(shù),一個(gè)設(shè)置最終動(dòng)畫值,一個(gè)設(shè)置持續(xù)時(shí)間,一個(gè)設(shè)置緩動(dòng)效果 - 在
render中,我們用interpolate方法創(chuàng)建marginLeft對(duì)象,包含inputRange和outputRange數(shù)組,我們使用此對(duì)象作為UI中message的style屬性 - 我們使用
Animated.div替代默認(rèn)的div - 我們將
animatedValue和marginLeft作為Animated.div的style屬性
Velocity React
Velocity React 是基于已經(jīng)存在的 Velocity 建立起來的
贊同者:上手容易,API 簡(jiǎn)單明了,相對(duì)其他庫(kù)更易于掌握
反對(duì)者:有些不得不克服的問題,比如 componentDidMount 后動(dòng)畫并沒有真正地起作用等,而且,它不跨平臺(tái)
下面是一個(gè)森破的示例
<VelocityComponent
animation={{ opacity: this.state.showSubComponent ? 1 : 0 }}
duration={500}
>
<MySubComponent/>
</VelocityComponent>
首先還是要用 yarn 或 npm 安裝它
yarn add velocity-react
在下面的實(shí)例中,我們將創(chuàng)建一個(gè)很酷的動(dòng)畫輸入

import { VelocityComponent } from 'velocity-react';
const VelocityLetter = ({ letter }) => (
<VelocityComponent
runOnMount
animation={{ opacity: 1, marginTop: 0 }}
duration={500}
>
<p style={styles.letter}>{letter}</p>
</VelocityComponent>
)
class VelocityApp extends Component {
state = {
letters: [],
}
onChange = (e) => {
const letters = e.target.value.split('');
const arr = [];
letters.forEach((l, i) => {
arr.push(<VelocityLetter letter={l} />)
});
this.setState({ letters: arr });
}
render() {
return (
<div className="App">
<div className="container">
<input onChange={this.onChange} style={styles.input} />
<div style={styles.letters}>
{
this.state.letters
}
</div>
</div>
</div>
);
}
}
const styles = {
input: {
marginBottom: 20,
padding: 8,
width: 200,
height: 40,
fontSize: 22,
backgroundColor: '#ddd',
border: 'none',
outline: 'none',
},
letters: {
display: 'flex',
height: 140,
},
letter: {
marginTop: 100,
fontSize: 22,
whiteSpace: 'pre',
opacity: 0,
}
}
- 從
velocity-react中 importVelocityComponent - 我們要?jiǎng)?chuàng)建一個(gè)
可重復(fù)使用的組件來滿足每個(gè)letter的動(dòng)畫 - 在這個(gè)組件中,我們將
animation的opacity設(shè)為1,marginTop設(shè)為0,這些值代表著傳入子組件的重寫值,即當(dāng)組件被創(chuàng)建時(shí),組件的opacity會(huì)由初始的0變?yōu)?1,marginTop會(huì)由初始的100變?yōu)?0,我們還設(shè)置了500 ms的持續(xù)時(shí)間,最后值得一提的是runOnMount屬性,它的意思是在組件掛載或創(chuàng)建完后執(zhí)行該動(dòng)畫 - 其中的
onChange方法會(huì)獲取用戶的每次輸入,并創(chuàng)建一個(gè)由VelocityLetter組成的新數(shù)組 - 在
render中,我們就使用該數(shù)組在UI中渲染letters
總結(jié)
總的來說,基本的動(dòng)畫,我會(huì)選擇 JS style,復(fù)雜的動(dòng)畫,我更偏向 React Motion。而對(duì)于 React Native,我還是堅(jiān)持使用 Animated,一旦 Animated 成熟,在 Web 中可能也會(huì)投入使用,目前,我真的很享受 React Motion