在 React Native 中对对象数组进行动画处理

Animate an array of objects in React Native

本文关键字:动画 处理 数组 对象 React Native      更新时间:2023-09-26

在 React 中,动画似乎总是绑定到 this.state 中的属性。但是,如果我在一个视图中有多个对象需要动画化,该怎么办?例如,如果我有一个包含多个图像的列表视图,并且我想在加载到列表视图时对这些图像的不透明度进行动画处理,该怎么办?

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的直接替代品,因此您可以像使用常规图像组件一样使用它。