Как применить анимацию в React JS - PullRequest
4 голосов
/ 12 июня 2019

Я использую библиотеку act-animated-css для применения анимации при изменении состояния в React JS.

Код выглядит следующим образом:

import ReactDOM from "react-dom";
import React, { Component } from "react";
import { Animated } from "react-animated-css";

const animationIn = "fadeInLeft";
const animationOut = "fadeOutLeft";
const animationDuration = 400; // in ms

const arr = [
  {
    id: 1,
    name: "Test"
  },
  {
    id: 2,
    name: "Test1"
  },
  {
    id: 3,
    name: "Test3"
  },
  {
    id: 4,
    name: "Test4"
  },
  {
    id: 5,
    name: "Test5"
  }
];

class Selection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selection: []
    };
    this.addSelection = this.addSelection.bind(this);
    this.removeItem = this.removeItem.bind(this);
  }

  addSelection(item) {
    const exists = this.state.selection.find(i => i.id === item.id);
    if (exists === undefined) {
      this.setState({ selection: [...this.state.selection, item] });
    }
  }

  removeItem(item) {
    this.setState({
      selection: this.state.selection.filter(i => i.id !== item.id)
    });
  }

  render() {
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          justifyContent: "space-between"
        }}
      >
        <div>
          <h2>Choose from the list</h2>
          {arr.map(item => {
            return (
              <div
                key={item.id}
                style={{ marginBottom: 5, cursor: "pointer" }}
                onClick={() => this.addSelection(item)}
              >
                {item.name}
              </div>
            );
          })}
        </div>

        <div>
          <h1>Selection</h1>
          {this.state.selection.length < 1 ? (
            <div>Nothing selected</div>
          ) : (
            this.state.selection.map(l => {
              return (
                <Animated
                  key={l.name}
                  animationIn={animationIn}
                  animationOut={animationOut}
                  animationInDuration={animationDuration}
                  animationOutDuration={animationDuration}
                  isVisible={true}
                >
                  <div key={l.id} style={{ marginBottom: 5 }}>
                    {l.name}
                    <button
                      onClick={() => this.removeItem(l)}
                      style={{ marginLeft: 5, cursor: "pointer" }}
                    >
                      Remove
                    </button>
                  </div>
                </Animated>
              );
            })
          )}
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Selection />, document.getElementById("root"));

Работает нормально, когда я нажимаю на какой-то элемент слева и добавляю его в состояние, но когда я удаляю его, он не работает.

Вот пример на песочнице.

Есть идеи, как применить анимацию и при удалении предметов из состояния?

Ответы [ 3 ]

2 голосов
/ 12 июня 2019

Вам нужно поиграть с state из props visible вашей анимации и добавить тайм-аут.

addSelection(item) {
    const exists = this.state.selection.find(i => i.id === item.id);
    if (exists === undefined) {
      this.setState({
        selection: [...this.state.selection, item],
        [`visibleAnimate${item.id}`]: true
      });
    }
  }

  removeItem(item) {
    this.setState(
      {
        [`visibleAnimate${item.id}`]: false
        // selection: this.state.selection.filter(i => i.id !== item.id)
      },
      () => {
        setTimeout(() => {
          this.setState({
            selection: this.state.selection.filter(i => i.id !== item.id)
          });
        }, 300);
      }
    );
  }

Здесь демо песочница .

0 голосов
/ 12 июня 2019

Вы должны переключить свойство isVisible, чтобы увидеть исходящую анимацию.Если компонент отключен, его нельзя оживить.

0 голосов
/ 12 июня 2019

С первого взгляда похоже, что вы удаляете анимацию с помощью элемента, поэтому она не воспроизводится.Работает ли это, если вы оборачиваете анимацию вокруг всего списка выбора, начиная с h1?

...