3

默认情况下,reactstrap 折叠组件总是垂直折叠,有什么技巧可以让它水平折叠吗?

也许我错过了一些东西...... https://reactstrap.github.io/components/collapse/

4

1 回答 1

3

因此,我创建了一个可以水平或垂直折叠两种方式的组件。垂直折叠仍在测试中,但它适用于水平折叠。

export default class Collapse extends Component {

    static props = {       
        isOpen: PropTypes.bool.isRequired,        
        vertical: PropTypes.bool,
        elementMaxLength: PropTypes.string,

        onOpen: PropTypes.func,
        onClose: PropTypes.func,
    }

    static defaultProps = {
        vertical: false,
        elementMaxLength: '300px',
        onOpen: () => console.log('Opened'),
        onClose: () => console.log('Closed'),
    }

   constructor(props) {
       super(props);

       this.state = {
        cssTarget: '_collapseH'
       }
   }

   componentDidMount() {
        if (this.props.vertical)
            this.setState({cssTarget: '_collapseV'})

        if (this.props.isOpen)
            this.collapse();
   }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (prevProps.isOpen !== this.props.isOpen)
            this.collapse();
   }

   collapse() {
    var content = this.refs.collapseDiv;
    if (content)
       if (this.decide(content))
          this.close(content)
       else
          this.open(content)    
   }

   decide(content) {
      if (this.props.vertical)
        return content.style.maxHeight;

      return content.style.maxWidth;
   }

   open(content) {
      this.assign(content, this.props.elementMaxLength);      
      this.props.onOpen();
   }

   close(content) {
      this.assign(content, null)
      this.props.onClose();
  }

  assign(content, value) {
    if (this.props.vertical)      
      content.style.maxHeight = value;
    else
      content.style.maxWidth = value;
  }

   render() {
    return (
          <div ref='collapseDiv' target={this.state.cssTarget}> 
            {this.props.children}
          </div>
    );
  }
}

所以基本上我们渲染一个 DIV 并引用它,这样我们就可以在我们的组件中使用this.refs. 我们在这个 DIV 中渲染所有传递给这个组件的子组件。

为了控制是否应该展开或折叠,我们使用了 isOpen 属性,它通过this.setState父组件内部从 TRUE 变为 FALSE。

当我们this.setState在父级内部使用时,它将触发对父级的重新渲染,同时也会触发对 Collapse 组件的重新渲染。这也将触发 componentDidUpdate我们将在哪里开始动画。

为了控制我使用 CSS 的动画:

div[target='_collapseV'] {
  display: flex;
  flex: 1;  
  overflow: hidden;
  background-color: maroon;

  max-height: 0;
  transition: max-height 1s ease-out;
}

div[target='_collapseH'] {
  display: flex;
  flex: 1;
  overflow: hidden;
  background-color: maroon;

  max-width: 0;    
  transition: max-width 1s ease;
}

目标属性设置在与我们设置ref属性相同的 DIV 中。如果 prop vertical设置为 true,那么我们的目标 att 将更改为_collapseV使组件垂直折叠。

为了触发动画,我们改变了函数内部的max-widthor值,max-height这个assign函数被称为 inside componentDidUpdate

唯一的缺点是您必须知道在此组件内呈现的内容的最大长度(宽度或高度),并在 prop 中设置elementMaxLength。它不必是相同的值,但 elementMaxLength 应该大于内容长度。

就是这样。

我真的不知道这是否是最好的方法,我确信还有很大的改进空间。但我认为这是一个很好的解决方案,工作正常,您不必安装任何软件包。

正如我之前所说的,垂直折叠仍然需要一些测试,但关键是要创建一些水平折叠的东西。

于 2018-06-22T15:06:45.847 回答