I have illustrated the problem in this CodePen
const Component = ({ structure }) => {
switch (structure) {
case 'nested':
return (
<div>
<AnimatedComponent />
</div>
);
case 'flat':
return
<AnimatedComponent />
;
}
};
AnimatedComponent
中有一些逻辑以动画方式更改组件的样式,例如在 1 秒的时间内将背景颜色从黑色更改为红色。通过在 AnimatedComponent
上更改颜色类来启动动画。 .有 CSS 来处理给定更改后的类的动画。
当将 DOM 结构从嵌套更改为平面时,HTML 元素被销毁并重新创建,过渡起始状态丢失(也就是浏览器不知道之前设置了哪个类,因为该元素是新创建的)。
我希望 React 做的是通过在新位置移动元素来更改 DOM 结构,而不是销毁和重新创建它们。
这可能吗?
我尝试使用 key
Prop <AnimatedComponent />
, 但它只修复了 DOM 变化的闪光。动画被跳过。参见 Codepen .谢谢Thomas Rooney对于这个建议。
我可以告诉 React 在 DOM 元素的位置更改后仅一次应用类更改吗?
最佳答案
Can I tell React to apply the class changes just one tick after the position of the DOM element was changed?
是的,这正是 setTimeout
函数的用途。复制你的第二个例子,你修复了闪烁,用 setTimeout
包装你的颜色 Action 调度(没有时间值,默认为 0),似乎可以解决你的问题。
onColorClick: () => {
setTimeout(() => {
dispatch({type: 'TOGGLE_COLOR'})
})
},
更新:我注意到在颜色变化之前添加一些时间更可靠(setTimeout
中的第二个参数,(fn, ms)
。我相信这是因为 setState
也是异步发生的。
onColorClick: () => {
setTimeout(() => {
dispatch({type: 'TOGGLE_COLOR'})
}, 100) <-- play around with this value
},
关于CSS Transitions 无法在 React Component 改变内部 DOM 结构后继续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642440/