温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Element values shifting and changing before transition with react-transition-group
javascript reactjs gatsby react-transition-group

javascript - 元素值在通过react-transition-group进行转换之前发生变化和变化

发布于 2020-03-27 11:00:36

react-transition-group在我正在从事的gatsby项目中使用软件包时,我注意到了这种现象。我有一个“标签”列表,这些标签是从另一个主列表中选取的,它们被添加到活动列表中。单击主列表中的标签将其添加到活动列表中,然后单击活动列表中的标签将其删除。您几乎希望这样的事情会起作用。

过渡作品不错,但转换时的标签在一个陌生的方式重新组织起来。我们有五个具有以下值的标签:

  • 无乳制品
  • Party Food
  • Family Sized
  • Low Cholesterol
  • Low Sodium

If you click the Family Sized tag to remove it, the following occurs:

  1. Family Sized disappears instantly
  2. Low Cholesterol and Low Sodium shift instantly to the left
  3. The last tag changes to Low Sodium instantly
  4. The last tag, now with the value of Low Sodium transitions out

The expected behavior is that the Family Sized tag transitions out from where it is in the middle of the group. I should note that it works fine if you remove the last tag from the active list, this only happens when removing a tag from any other position.

Here is a slowed-down GIF of the transition and here is my code:

<TransitionGroup className='tag-container'>
  {filter.map((tag, index) => {
    return (
      <CSSTransition key={index} timeout={250} classNames={`tag`}>
        <TagButton value={tag} onClick={onClickFunction} className={`${screenStyle} active`}>{tag}</TagButton>
      </CSSTransition>
    )
  })}
</TransitionGroup>
  • filter is an array destructured from the component's state.
  • 有一个<StaticQuery>gatsby在相同的使用render()如果该事务的部件的方法。
  • <TagButton>是从一个风格的部件styled-components包,而不是一个单独进口组合。

查看更多

查看更多

提问者
Shnibble
被浏览
209
adel 2019-07-02 22:17

在数组方法中添加特定的标识符并将每个元素的键设置为map方法中的每个标识符将解决您的问题。

import React from "react";
import ReactDOM from "react-dom";
import { Button } from "react-bootstrap";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import "bootstrap/dist/css/bootstrap.css";
import "./styles.css";
import uuid from "uuid";

function App() {
  const [items, setitems] = React.useState([
    { id: uuid(), name: "Dairy Free" },
    { id: uuid(), name: "Party Food" },
    { id: uuid(), name: "Family Sized" },
    { id: uuid(), name: "Low Cholesterol" },
    { id: uuid(), name: "Low Sodium" }
  ]);
  const removeitem = item => {
    setitems(items.filter(itemname => itemname.id !== item));
  };
  return (
    <div className="App">
      <TransitionGroup className="todo-list">
        {items.map(data => (
          <CSSTransition timeout={500} classNames="item" key={data.id}>
            <Button className="m-2" onClick={() => removeitem(data.id)}>
              {data.name}
            </Button>
          </CSSTransition>
        ))}
      </TransitionGroup>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

这个问题已经在这里解决,因此请结帐以了解这种奇怪的行为。