首页 > 解决方案 > 负载可扩展组件最小化

问题描述

我正在尝试将我的组件加载到最小化,但到目前为止我尝试过的任何东西似乎都不起作用。下面是我的组件:它是一个带有下拉箭头的可折叠组件,在父组件中有一堆,但它们都加载展开。将它们全部最小化然后用户可以选择扩展它们会更干净。

import { StyleSheet,Text,View,Image,TouchableHighlight,Animated } from 'react-native';
import React from 'react';

export class ExpanderView extends React.Component {
  constructor(props) {
    super(props);
    this.icons = {
      'up': require('./images/Arrowhead-01-128.png'),
      'down'  : require('./images/Arrowhead-Down-01-128.png')
    };
    this.state = {
      animation: new Animated.Value(),
      expanded: true
    };

  }

  toggle() {
    let initialValue    = this.state.expanded? this.state.maxHeight + this.state.minHeight : this.state.minHeight,
        finalValue      = this.state.expanded? this.state.minHeight : this.state.maxHeight + this.state.minHeight;

    this.setState({
      expanded: !this.state.expanded
    });

    this.state.animation.setValue(initialValue);
    Animated.spring(
      this.state.animation, 
      {toValue: finalValue}
    ).start();
  }

  _setMaxHeight(event) {
    this.setState({
      maxHeight: event.nativeEvent.layout.height
    });
  }

  _setMinHeight(event) {
    this.setState({
      minHeight: event.nativeEvent.layout.height
    });
  }

  render() {
    let icon = this.icons['down'];

    if (this.state.expanded) {
      icon = this.icons['up'];
    }
    return (
      <Animated.View style={[styles.container, {height: this.state.animation}]}>
         <View style={styles.titleContainer} onLayout={this._setMinHeight.bind(this)}>
          {/* // Passing props as state variable ain't right */}
            <Text style={styles.title}>{this.props.title}</Text>
            <TouchableHighlight
              style={styles.button}
              onPress={this.toggle.bind(this)}
              underlayColor="#f1f1f1">

              <Image style={styles.buttonImage} source={icon}></Image>

            </TouchableHighlight>
          </View>

          <View style={styles.body} onLayout={this._setMaxHeight.bind(this)}>
            {this.props.children}
          </View>
      </Animated.View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    backgroundColor:'#fff',
    margin: 10,
    overflow: 'hidden'
  },
  titleContainer: {
    flex: 1,
    flexDirection: 'row'
  },
  inputWrap: {
    flex: 1
  },
  title: {
    flex: 1,
    padding: 10,
    color: '#2a2f43',
    fontWeight: 'bold',
  },
  button: {

  },
  buttonImage: {
    width: 30,
    height: 25
  },
  body: {
    padding: 10,
    paddingTop: 0
  }
});

我猜想操纵样式是可以实现的。谢谢你。

标签: react-native

解决方案


我现在找到了一种解决方法:

componentDidMount() {
    setTimeout(() => {
      this.toggle();
    }, 45); 
  }

它运作良好,但这不是所需的行为。


推荐阅读