Hide/Show components in react native

后端 未结 24 2070
囚心锁ツ
囚心锁ツ 2020-12-07 08:43

I\'m really new to React Native and I\'m wondering how can I hide/show a component.
Here\'s my test case:



        
24条回答
  •  忘掉有多难
    2020-12-07 09:15

    I had the same issue where I would want to show / hide Views, but I really didn't want the UI jumping around when things were added/removed or necessarily to deal with re-rendering.

    I wrote a simple Component to deal with it for me. Animated by default, but easy to toggle. I put it on GitHub and NPM with a readme, but all the code is below.

    npm install --save react-native-hideable-view

    import React, { Component, PropTypes } from 'react';
    import { Animated  } from 'react-native';
    
    class HideableView extends Component {
      constructor(props) {
        super(props);
        this.state = {
          opacity: new Animated.Value(this.props.visible ? 1 : 0)
        }
      }
    
      animate(show) {
        const duration = this.props.duration ? parseInt(this.props.duration) : 500;
        Animated.timing(
          this.state.opacity, {
            toValue: show ? 1 : 0,
            duration: !this.props.noAnimation ? duration : 0
          }
        ).start();
      }
    
      shouldComponentUpdate(nextProps) {
        return this.props.visible !== nextProps.visible;
      }
    
      componentWillUpdate(nextProps, nextState) {
        if (this.props.visible !== nextProps.visible) {
          this.animate(nextProps.visible);
        }
      }
    
      render() {
        if (this.props.removeWhenHidden) {
          return (this.visible && this.props.children);
        }
        return (
          
            {this.props.children}
          
        )
      }
    }
    
    HideableView.propTypes = {
      visible: PropTypes.bool.isRequired,
      duration: PropTypes.number,
      removeWhenHidden: PropTypes.bool,
      noAnimation: PropTypes.bool
    }
    
    export default HideableView;
    

提交回复
热议问题