首页 > 解决方案 > 为什么 React 组件上的 CSS 过渡只在一个方向上起作用?

问题描述

我有 4 个 div,我想在按向左或向右箭头键时移动其中一个。这个移动应该是一个过渡而不是瞬时的,但由于某种原因,这个过渡只有在我向左移动时才有效。

我认为这与key道具或 div 被卸载有关,但在尝试了一堆不同的东西之后,我不再确定了。

请看一下:https ://codesandbox.io/s/confident-grothendieck-oou90?file=/src/App.js

有谁知道发生了什么?

标签: javascriptreactjscss-transitions

解决方案


在样式中,您只添加了 transition:left 0.3s. 所以它不适合正确的。您可以将其更改为transition:all 0.3s

.tile {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  background-color: lightgrey;
  font-size: 32px;
  transition: all 0.3s ease;
}

推荐阅读