我正在尝试使用 React Motion 创建一个基本动画:我有两个元素,可以根据组件状态显示其中的任何一个。当状态发生变化时,我希望一个元素替换另一个元素。替换动画是向左滑动和淡出离开元素的组合。
问题:当状态改变时,离开元素与进入元素变得无法区分。
插图:在这里,在我重现问题的代码笔中,单击彩色形状将更改组件的状态并替换元素。请注意,离开的组件与进入的组件相同(例如,当单击一个圆圈时,它会变为正方形并离开)。我希望离开的元素保持其初始形状。
下面是来自 CodePen 的组件代码副本:
const spring = ReactMotion.spring;
const TransitionMotion = ReactMotion.TransitionMotion;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
mode: 'foo'
}
}
changeMode() {
const { mode: currentMode } = this.state;
this.setState({
mode: currentMode === 'foo' ? 'bar' : 'foo'
});
}
willEnter() {
return { opacity: 0, translateX: 200 };
}
willLeave() {
return { opacity: spring(0), translateX: spring(-200, { stiffness: 140, damping: 20 }) };
}
render() {
const { mode } = this.state;
const styles = [mode].map(mode => {
return {
key: mode,
style: {
opacity: spring(1),
translateX: spring(0, { stiffness: 140, damping: 12 })
}
}
});
return (
<div className="container">
<TransitionMotion
styles={styles}
willEnter={this.willEnter}
willLeave={this.willLeave}
>
{ interpolatedStyles =>
<div style={{ position: 'relative' }}>
{
interpolatedStyles.map(config => {
return mode === 'foo' ? this.renderFoo(config) : this.renderBar(config);
})
}
</div>
}
</TransitionMotion>
<div className="label"> Click the shape </div>
</div>
);
}
renderFoo(config) {
console.log('config', config);
return (
<div
key={config.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '150px',
height: '150px',
borderRadius: '100%',
backgroundColor: 'red',
opacity: config.style.opacity,
transform: `translateX(${config.style.translateX}%)`
}}
onClick={ () => this.changeMode() }
/>
);
}
renderBar(config) {
return (
<div
key={config.key}
style={{
...config.styles,
position: 'absolute',
top: 0,
left: 0,
width: '150px',
height: '150px',
backgroundColor: 'blue',
opacity: config.style.opacity,
transform: `translateX(${config.style.translateX}%)`
}}
onClick={ () => this.changeMode() }
/>
);
}
}
您能否建议如何修复动画以使离开的元素在视觉上是正确的?