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

前端 未结 5 1732
面向向阳花
面向向阳花 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:39

    i follow step on some blog then i have same condition with it. so i made a changes after clue from others here. my post maybe is to late. but i wish will be help others.

    import React from 'react';
    import {
      Text,
      View,
      TouchableOpacity,
      Image,
      Animated,
      StyleSheet
    } from 'react-native'
    import styles from './styles' //put styles from another file
    
    class PanelExpanding extends Component{
      constructor(props) {
        super(props)
        this.state = {
          expanded: false, //step 1 
          animation: new Animated.Value()
        }
    
        this.icons = {
          'up': require('../../..assets/images/up.png'),
          'down': require('../../../assets/images/down.png')
        }
      }
    
      toggle(){
        let finalValue    = this.state.expanded? this.state.maxHeight + this.state.minHeight : this.state.minHeight,
            initialValue  = this.state.expanded? this.state.minHeight : this.state.maxHeight + this.state.minHeight;
        //step 2, this needed, if we use !this.state.expanded i don't know how it wont changes at first
        if(this.state.expanded === true){
          return this.setState({ expanded : false })
        } else {
          return this.setState({ expanded : true })
        }
        this.state.animation.setValue(initialValue);
        Animated.spring(
            this.state.animation,
            { toValue: finalValue }
        ).start();
      }
    
    
      _setMinHeight(event){
        this.setState({
            minHeight : event.nativeEvent.layout.height
        });
      }
    
      _setMaxHeight(event){
        this.setState({
            maxHeight : event.nativeEvent.layout.height
        });
      }
    
    
      render(){
        let icon = this.icons['down'],
            textSwap = 'SHOWMORE'
    
        if(this.state.expanded){
          icon = this.icons['up'],
          textSwap = 'SHOWLESS'
        }
    
        return (
          
            
              
                  
                      {textSwap}
                      
                  
              
    
              //step 3, add this to initial when first render is false
              {this.state.expanded && 
                
                  {this.props.children}
                
              }
            
          
        )
      }
    }
    
    export default PanelExpanding
    

提交回复
热议问题