我正在尝试使用 React Motion UI Pack为我的侧边导航制作滑入/滑出动画。就是这样:
constructor(props){
super(props);
this.state = {
isThere: false,
showOverlay: false
}
this.updatePredicate = this.updatePredicate.bind(this);
this.handleToggleClick = this.handleToggleClick.bind(this);
this.handleOverlayClick = this.handleOverlayClick.bind(this);
}
componentDidMount() {
this.updatePredicate();
window.addEventListener("resize", this.updatePredicate);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updatePredicate);
}
updatePredicate() {
this.setState({ isThere: window.innerWidth > this.props.breakWidth })
}
handleToggleClick(){
this.setState({
isThere: true,
showOverlay: true
})
}
handleOverlayClick(){
this.setState({
isThere: false,
showOverlay: false
});
}
let sidenav = (
<Tag {...attributes} className={classes} key="sidenav">
<ul className="custom-scrollbar">
{src &&
<li>
<div className="logo-wrapper">
<a href={href}>
<img src={src} className="img-fluid"/>
</a>
</div>
</li>
}
{children}
</ul>
</Tag>
);
return (
<div>
{ isThere ? (
<Transition
component={false}
appear={{ opacity: 0.2, translateX: -300 }}
enter={{ opacity: 1, translateX: 0 }}
leave={{ opacity: 0.2, translateX: -300 }}
>
{ sidenav }
</Transition>
) : (
<Button color="primary" onClick={this.handleToggleClick} key="sideNavToggles">ClickMe</Button>
) }
{showOverlay && (
<div id="sidenav-overlay" onClick={this.handleOverlayClick} key="overlay"></div>
)}
</div>
);
}
}
该实用程序看起来很棒,但有些东西我无法理解。我的组件根据 breakWith
Prop 呈现按钮或 sidenav。单击呈现的按钮会导致 SideNav 滑入,这次是与叠加层一起滑入。 Transition
允许平滑的滑入动画,但现在我想在点击叠加层时应用滑出动画。
几个小时过去了,我开始觉得这是不可能的。组件的渲染是有条件的和基于状态的(isThere?(...
render()
中的部分),对吗?因为包不提供 willLeave
Prop ,似乎没有时间在状态更改和重新渲染之间为 leave
设置动画,条件渲染元素已经丢失。
还是我遗漏了什么?
最佳答案
是的 - 找到了答案 here有效地解决了问题。为了解决这个问题,我将组件的条件逻辑上移,创建了适当的变量,并将其封装在一个<Transition>
中。在 render()
.如果这里要吸取教训,那就是 <Transition>
来自 Reakt Motion UI Pack (也许还有其他地方)不会触发它的 leave
如果动画被条件语句包围,则无法与 ternary operator
一起使用如果你不想要 false
组件也将被动画化。
关于javascript - 如何为条件渲染的组件设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190529/