可以通过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写一个收缩功能收缩的时候采用滑动高度自动根据内容变化

原文地址: http://www.cveoy.top/t/topic/gfMF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录