当div的内容被React脚本更改时使用CSS Transition

70gysomp  于 2023-04-13  发布在  React
关注(0)|答案(2)|浏览(111)

我使用一个状态来渲染一个div中的不同组件,因此改变了它的高度。我希望我的css高度转换在改变发生时执行。请有人帮助我。
React代码:

<div className="venue-details">
            {venue ? 
                <>
                    <span>Date: &nbsp;To Be Announced... </span><br />
                    <span>Location: &nbsp; My Location</span><br />
                </>:
                <>
                    <span>Click to view</span>
                </>
            }
</div>

CSS代码:

.venue-details{
    position: relative;
    font-size: 20px;
    padding-left: 10%;
    padding-bottom: 30px;
    padding-right: 10%;
    transition: height 1s ease-in-out;
}
qij5mzcb

qij5mzcb1#

你可以使用ReactTransitionGroup来动画你的div元素的高度:

import { CSSTransition } from 'react-transition-group';
    // ...
    
    <CSSTransition
      in={venue}
      timeout={1000}
      classNames="venue-details"
    >
      <div className="venue-details">
        {venue ? (
          <>
            <span>Date: &nbsp;To Be Announced... </span><br />
            <span>Location: &nbsp; My Location</span><br />
          </>
        ) : (
          <>
            <span>Click to view</span>
          </>
        )}
      </div>
    </CSSTransition>

css:

.venue-details-enter {
  height: 0;
}

.venue-details-enter-active {
  height: [desired-height];
  transition: height 1s ease-in-out;
}

.venue-details-exit {
  height: [desired-height];
}

.venue-details-exit-active {
  height: 0;
  transition: height 1s ease-in-out;
}
l0oc07j2

l0oc07j22#

问题是你在dom中添加/删除你的span,而不是改变它们上的类。试试类似这样的东西:

<div className={venueDisplayClass} >
   <p className="withVenue">
        Date: TBA
   </p>
   <p className="withVenue">Location: TBA</p>
   <button className="withoutVenue" onClick={setVenueDisplayClass('showVenue')}>Click to View</button>
</div>

然后你的css可以更像

.showVenue .withVenue {
   height: auto;
   transition: /* your transition */
}
.showVenue .withoutVenue {
  height: 0;
  transition: /* your transition */
}

.hideVenue .withVenue {
   height: 0;
}

.hideVenue .withoutVenue {
   height: auto;
}

相关问题