可以通过 state 来实现收缩功能,具体步骤如下:

  1. 在 constructor 中初始化 state,包括是否展开和高度
constructor(props) {
  super(props);
  this.state = {
    isExpanded: true,
    height: 'auto'
  };
}
  1. 在 div 中添加点击事件,切换 isExpanded 的值,并根据 isExpanded 的值设置高度
<div onClick={() => this.setState({isExpanded: !this.state.isExpanded, height: this.state.isExpanded ? 0 : 'auto'})}>
  ...
</div>
  1. 在 div 的 style 属性中设置过渡效果和高度
<div style={{  
  transition: 'height 0.3s ease',
  height: this.state.height
}} onClick={() => this.setState({isExpanded: !this.state.isExpanded, height: this.state.isExpanded ? 0 : 'auto'})}>
  ...
</div>

完整代码如下:

class ExpandableDiv extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isExpanded: true,
      height: 'auto'
    };
  }

  render() {
    return (
      <div style={{  
        transition: 'height 0.3s ease',
        height: this.state.height
      }} onClick={() => this.setState({isExpanded: !this.state.isExpanded, height: this.state.isExpanded ? 0 : 'auto'})}>
        ...
      </div>
    );
  }
}
ReactJS 实现 Div 收缩功能:滑动动画和高度自适应