如果想要学习react-native的动画效果,这个组件是值得好好看看。
条件:在市场,商店搜索下载安装 f8 app ,还要有一个fb的账号,否则在手机端看不到这个效果。
在f8app中状态都是由redux来控制的,所以在看这个代码的时候要有一个流程知道数据去了哪里,因为代码不在一个文件中。f8app的redux使用比较灵活,没有标准的container文件夹,UI组件和redux的连接都是在需要状态的组件中直接使用connect方法来注入需要的状态和方法名。如果在组件中看到connect函数感到很困惑,可以再返回去看看redux文档关于connect的内容,注意里面对state注入的描述。
这个组件的数据流程是:
AddToSeheduleButton.js-->f8sessionDetail.js-->redux(action->reducer->store->)-->connect(mapStateToProps)-->AddToSeheduleButton
在中间的redux发生了state的翻转,代码据此来改变按钮的颜色,文字的变化
剩下的问题就是组件自身的动画效果的变化。
如果是对redux不太熟,其实可以在onPress的函数中直接使用setState来改变一个状态标记位就可以了。这样这个组件我们就可以直接拿来研究,不用管redux的处理过程.但是最好要掌握redux。
点击添加之前的样式
点击添加之后的样式
首先放上代码。
//f8app/js/tabs/schedule/AddToScheduleButton.js
use strict';
var Image = require('Image');
var LinearGradient = require('react-native-linear-gradient');
var React = require('React');
var StyleSheet = require('StyleSheet');
var { Text } = require('F8Text');
var TouchableOpacity = require('TouchableOpacity');
var View = require('View');
var Animated = require('Animated');
type Props = {
isAdded: boolean;
onPress: () => void;
addedImageSource?: number;
style: any;
};
const SAVED_LABEL = 'Saved to your schedule';
const ADD_LABEL = 'Add to my schedule';
class AddToScheduleButton extends React.Component {
constructor(props: Props) {
super(props);
this.state = {
anim: new Animated.Value(props.isAdded ? 1 : 0),
};
}
render() {
const colors = this.props.isAdded ? ['#4DC7A4', '#66D37A'] : ['#6A6AD5', '#6F86D9'];
const addOpacity = {
opacity: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
}),
transform: [{
translateY: this.state.anim.interpolate({
inputRange: [0, 1], //y轴的变化
outputRange: [0, 40],//映射的变化
}),
}],
};
const addOpacityImage = {
opacity: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [1, 0],
}),
transform: [{
translateY: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [0, 80],
}),
}],
};
const addedOpacity = {
opacity: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
}),
transform: [{
translateY: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [-40, 0],
}),
}],
};
const addedOpacityImage = {
opacity: this.state.anim.interpolate({
inputRange: [0.7, 1],
outputRange: [0, 1],
}),
transform: [{
translateY: this.state.anim.interpolate({
inputRange: [0, 1],
outputRange: [-80, 0],
}),
}],
};
return (
<TouchableOpacity
accessibilityLabel={this.props.isAdded ? SAVED_LABEL : ADD_LABEL}
accessibilityTraits="button"
onPress={this.props.onPress}
activeOpacity={0.9}
style={[styles.container, this.props.style]}>
<LinearGradient
start={[0.5, 1]} end={[1, 1]}
colors={colors}
collapsable={false}
style={styles.button}>
<View style={{flex: 1}}>
<View style={styles.content} collapsable={false}>
<Animated.Image
source={this.props.addedImageSource || require('./img/added.png')}
style={[styles.icon, addedOpacityImage]}
/>
<Animated.Text style={[styles.caption, addedOpacity]}>
<Text>{SAVED_LABEL.toUpperCase()}</Text>
</Animated.Text>
</View>
<View style={styles.content}>
<Animated.Image
source={require('./img/add.png')}
style={[styles.icon, addOpacityImage]}
/>
<Animated.Text style={[styles.caption, addOpacity]}>
<Text>{ADD_LABEL.toUpperCase()}</Text>
</Animated.Text>
</View>
</View>
</LinearGradient>
</TouchableOpacity>
);
}
componentWillReceiveProps(nextProps: Props) {
if (this.props.isAdded !== nextProps.isAdded) {
const toValue = nextProps.isAdded ? 1 : 0;
Animated.spring(this.state.anim, {toValue}).start();
}
}
}
const HEIGHT = 50;
var styles = StyleSheet.create({
container: {
flexDirection: 'row',
height: HEIGHT,
overflow: 'hidden',
},
button: {
flex: 1,
borderRadius: HEIGHT / 2,
backgroundColor: 'transparent',
paddingHorizontal: 40,
},
content: {
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
icon: {
marginRight: 12,
},
caption: {
letterSpacing: 1,
fontSize: 12,
color: 'white',
},
});
module.exports = AddToScheduleButton;
//下面是一段难懂的代码,上面一句已经导出代码了,这里这一句是什么意思?
//[到这里找答案](https://f8-app.liaohuqiu.net/tutorials/building-the-f8-app/design/)
module.exports.__cards__ = (define) => {
let f;
setInterval(() => f && f(), 1000);
define('Inactive', (state = true, update) =>
<AddToScheduleButton isAdded={state} onPress={() => update(!state)} />);
define('Active', (state = false, update) =>
<AddToScheduleButton isAdded={state} onPress={() => update(!state)} />);
define('Animated', (state = false, update) => {
f = () => update(!state);
return <AddToScheduleButton isAdded={state} />;
});
};
这个组件是在sessionDetail.js中使用的,在这里导入的onPress的方法.这里的session是schedule中的内容
//f8app/js/tabs/f8sessionDetail.js
var {addToSchedule, removeFromScheduleWithPrompt} = require('../../actions');//这一句是比较难理解的,f8这个组件用
//redux connec进行了包装,改变state的方法是在redux中
//具体细节就不列了,从图上可以看到实际是state发生了翻转
<View style={styles.actions}>
<AddToScheduleButton
addedImageSource={isReactTalk && require('./img/added-react.png')}
isAdded={this.props.isAddedToSchedule}
onPress={this.toggleAdded} //props传入的方法
/>
</View>
//实际的toggleAdded方法
toggleAdded: function() {
if (this.props.isAddedToSchedule) {
this.props.removeFromScheduleWithPrompt();
} else {
this.addToSchedule();
}
},
//这里的两个方法
addToSchedule: function() {
if (!this.props.isLoggedIn) {
this.props.navigator.push({
login: true, // TODO: Proper route
callback: this.addToSchedule,
});
} else {
this.props.addToSchedule();
if (this.props.sharedSchedule === null) {
setTimeout(() => this.props.navigator.push({share: true}), 1000);
}
}
},
});
reducer里面发生的状态的变化
//f8app/js/reducer/schedule.js
'use strict';
import type {Action} from '../actions/types';
export type State = {
[id: string]: boolean;
};
function schedule(state: State = {}, action: Action): State {
switch (action.type) {
case 'SESSION_ADDED':
let added = {};
added[action.id] = true; //状态改变
return {...state, ...added};
case 'SESSION_REMOVED':
let rest = {...state};
delete rest[action.id]; //删除状态
return rest;
case 'LOGGED_OUT':
return {};
case 'RESTORED_SCHEDULE':
let all = {};
action.list.forEach((session) => {
all[session.id] = true;
});
return all;
}
return state;
}
module.exports = schedule;