Make animated collapsible card component, with initial props to show or hide

前端 未结 5 1734
面向向阳花
面向向阳花 2021-01-14 03:12

Background

Using React Native I was able to make collapsible card component. On Icon click the card slides up hiding its content, or expands showing

5条回答
  •  余生分开走
    2021-01-14 03:25

    Made a brand new one for you. Simple and works fine.

    Note: no state required for this component. fewer state, better performance.

    Maybe you could modify your own style on top of this =)

    class Card extends Component {
        anime = {
            height: new Animated.Value(),
            expanded: false,
            contentHeight: 0,
        }
    
        constructor(props) {
            super(props);
    
            this._initContentHeight = this._initContentHeight.bind(this);
            this.toggle = this.toggle.bind(this);
    
            this.anime.expanded = props.expanded;
        }
    
        _initContentHeight(evt) {
            if (this.anime.contentHeight>0) return;
            this.anime.contentHeight = evt.nativeEvent.layout.height;
            this.anime.height.setValue(this.anime.expanded ? this._getMaxValue() : this._getMinValue() );
        }
    
        _getMaxValue() { return this.anime.contentHeight };
        _getMinValue() { return 0 };
    
        toggle() {
            Animated.timing(this.anime.height, {
                toValue: this.anime.expanded ? this._getMinValue() : this._getMaxValue(),
                duration: 300,
            }).start();
            this.anime.expanded = !this.anime.expanded;
        }
    
        render() {
            return (
                
                    
                        
                            {this.props.title}
                        
                    
    
                    
                        {this.props.children}
                    
                
            );
        }
    }
    

    Usage:

    
        Hello, this is first line.
        Hello, this is second line.
        Hello, this is third line.
    
    

    Visual result: (only second card start with expanded={true}, others with expanded={false})

提交回复
热议问题