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

标签 javascript ios react-native

在 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/

相关文章:

java - 在java中使用ScriptEngine,如何提取函数列表?

javascript - c3 chart.load 多个图表

ios - 切换 View Controller 后第二次调用方法的问题

ios - 如何使用 uiactivityviewcontroller 修复默认弹出菜单

javascript - 在yield调用完成之前yield put被触发

javascript - 使用按钮提交文本框输入

javascript - 两个同名的函数,我想调用div处于事件状态的函数

ios - 终止应用程序后保存数组索引

react-native - 在 React-Native 应用程序中使用带有授权 header 的 Axios GET

javascript - React Native 无法解决错误