多个React-Native组件的可重用动画

时间:2018-01-30 14:38:12

标签: javascript android ios animation react-native

我正在尝试为一系列组件创建默认的offsetY动画。这些组件从不同的外部文件加载到App.js.目前我在每个组件中使用以下动画设置,但我想找到一个DRY(不要重复自己)的方式来实现它。如何只设置一个动画并避免重复?是否需要在App.js中声明动画,还是可以在外部文件中创建动画?

有人能指出我正确的方向吗?提前谢谢!

组件设置

import React, { Component } from 'react';
import {
  Animated,
  View,
  Text,
  StyleSheet,
  DeviceEventEmitter
} from 'react-native';

// Custom **********************************************************************
import styles from '../styles'

export class BlueberryComp extends Component {
  constructor(props) {
    super(props)
    this.state = {
      offsetY: new Animated.Value(0),
      fadeIn: new Animated.Value(0)
    }
  }

  componentDidMount() {
    Animated.parallel([
      Animated.timing(
        this.state.offsetY,
        {
          toValue: -100,
          duration: 1000,
        }),
      Animated.timing(
        this.state.fadeIn,
        {
          toValue: 1,
          duration: 1000,
        }
      )
    ]).start();
  }


  render() {
    let { offsetY, fadeIn } = this.state;

    return (
      <Animated.View style={{ opacity: fadeIn, transform: [{ translateY: offsetY }] }}>
        <Text style={styles.h1}>{this.props.name}</Text>
      </Animated.View>
    );
  }
}

App.js,这里我使用renderIf将每个组件加载到渲染视图中。

  render() {
    const { isIce, isMint, isBlueberry } = this.state
    return (
        <View style={styles.container}>
            {renderIf(isIce, <IceComp name={this.state.name} />)}
            {renderIf(isMint, <MintComp name={this.state.name} />)}
            {renderIf(isBlueberry, <BlueberryComp name={this.state.name} />)}
        </View>
    )
  }

1 个答案:

答案 0 :(得分:0)

所以,经过多次尝试和失败后,我从Gosha Arinich那里找到了这个很好的例子。我希望这将有助于未来的用户解决我遇到的同样问题。不过,谢谢@Cruiser。

动画外观&amp;在React Native中消失 https://goshakkk.name/react-native-animated-appearance-disappearance/