在 React 中,动画似乎总是绑定(bind)到 this.state
中的属性。但是,如果 View 中有多个需要设置动画的对象怎么办?例如,如果我有一个包含多个图像的 ListView,并且我想在这些图像加载到 ListView 中时对它们的不透明度进行动画处理,该怎么办?
render() {
//var _scrollView: ScrollView;
return (
<View style={styles.container}>
<ScrollView
style={styles.scrollView}>
<ListView
initialListSize={1}
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
style={styles.postList}
/>
</ScrollView>
</View>
);
}
renderRow(post) {
//var postItemHeight = windowSize / 2
return (
<View style={styles.postItem}>
<Image
style={styles.postImage}
source={{uri: post.cover_image}}
onLoad={(e) => this.imageLoaded()}>
</Image>
</View>
);
}
imageLoaded() {
// now animate the image opacity
// for every image that is loaded into the listview
}
最佳答案
没有理由 Animated
值需要存在于组件状态中 - 这正是示例展示如何做到这一点的方式。如果您愿意,您可以在状态中保留一组 Animated
值,将它们放入您的 Flux 存储中,或者以您想要的方式进行。
然而,在您的特定情况下,最简单的解决方案是创建一个组件来表示您的 ListView
的单个图像行。然后您可以使用那个组件的单独状态来管理它的动画。
例如:
const FadeImage = React.createClass({
displayName: 'FadeImage',
propTypes: Image.propTypes,
getInitialState() {
return {
opacity: new Animated.Value(0)
};
},
setNativeProps(nativeProps) {
this._image.setNativeProps(nativeProps);
},
fadeIn() {
Animated.spring(this.state.opacity, {
toValue: 1,
friction: 10,
tension: 60
}).start();
},
render() {
return (
<Animated.View style={{opacity: this.state.opacity}}>
<Image {...this.props} onLoad={this.fadeIn} ref={component => this._image = component} />
</Animated.View>
);
}
});
它是 Image
的直接替代品,因此您可以像使用常规 Image 组件一样使用它。
关于javascript - 在 React Native 中对对象数组进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35934668/