React Native: run animation on hide

I have an element that controls the rendering of a child element. (A TouchableHighlight that sets some state to onPress). In the child method, componentDidMountI create Animated.springand startit. This works for login, but I need to do the same animation in reverse order to exit (it's like a box). componentWillUnmountrunning too fast for Animated.springto even start working.

How do I handle file exit animation?

+4
source share
2 answers

I have implemented a component FadeInOutthat will animate a component in or out when its property changes isVisible. I did this because I wanted to avoid explicitly handling the visibility state in components that need to enter / exit animations.

<FadeInOut isVisible={this.state.someBooleanProperty} style={styles.someStyle}>
  <Text>Something...</Text>
</FadeInOut>

This implementation uses delayed attenuation because I use it to display a progress indicator, but you can change it to use any animation you want, or generalize it to accept animation parameters as props:

'use strict';

import React from 'react-native';

const {
  View,
  Animated,
  PropTypes
} = React;

export default React.createClass({
  displayName: 'FadeInOut',
  propTypes: {
    isVisible: PropTypes.bool.isRequired,
    children: PropTypes.node.isRequired,
    style: View.propTypes.style
  },

  getInitialState() {
    return {
      view: this.props.children,
      opacity: new Animated.Value(this.props.isVisible ? 1 : 0)
    };
  },

  componentWillReceiveProps(nextProps) {
    const isVisible = this.props.isVisible;
    const shouldBeVisible = nextProps.isVisible;

    if (isVisible && !shouldBeVisible) {
      Animated.timing(this.state.opacity, {
        toValue: 0,
        delay: 500,
        duration: 200
      }).start(this.removeView);
    }

    if (!isVisible && shouldBeVisible) {
      this.insertView();
      Animated.timing(this.state.opacity, {
        toValue: 1,
        delay: 500,
        duration: 200
      }).start();
    }
  },

  insertView() {
    this.setState({
      view: this.props.children
    });
  },

  removeView() {
    this.setState({
      view: null
    });
  },

  render() {
    return (
      <Animated.View
        pointerEvents={this.props.isVisible ? 'auto' : 'none'}
        style={[this.props.style, {opacity: this.state.opacity}]}>
        {this.state.view}
      </Animated.View>
    );
  }
});
+7
source

, . , , . , componentDidMount, TouchableHighlight , , .

, "", , . (, ), . , , .

+1

Source: https://habr.com/ru/post/1625951/


All Articles