【问题标题】:React-spring animation only works at first renderReact-spring 动画仅在第一次渲染时有效
【发布时间】:2019-01-13 04:04:38
【问题描述】:

我尝试为数组中的新条目设置动画,因为它们以 react-spring 出现。它在第一次渲染时工作得很好,但在更新时没有动画

这是一个代码沙箱,我在其中以一定间隔重现了该问题:https://codesandbox.io/s/01672okvpl

import React from "react";
import ReactDOM from "react-dom";
import { Transition, animated, config } from "react-spring";

import "./styles.css";

class App extends React.Component {
  state = { fake: ["a", "b", "c", "d", "e", "f"] };

  fakeUpdates = () => {
    const [head, ...tail] = this.state.fake.reverse();
    this.setState({ fake: [...tail, head].reverse() });
  };

  componentDidMount() {
    setInterval(this.fakeUpdates, 2000);
  }

  componentWillUnmount() {
    clearInterval(this.fakeUpdates);
  }

  render() {
    const { fake } = this.state;
    return (
      <div className="App">
        {fake.map((entry, index) => (
          <Transition
            native
            from={{
              transform: `translateY(${index === 0 ? "-200%" : "-100%"})`
            }}
            to={{ transform: "translateY(0)" }}
            config={config.slow}
            key={index}
          >
            {styles => <animated.div style={styles}>{entry}</animated.div>}
          </Transition>
        ))}
      </div>
    );
  }
}

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

我尝试使用Spring 和Transition 得到相同的结果。

【问题讨论】:

    标签: javascript reactjs react-spring


    【解决方案1】:

    您的问题是因为您的密钥没有更新。由于您将 0 的键替换为 0 的键,因此它认为它已经应用了转换。

    当把key改成${entry}_${index}时,会把key更新为'a_0',然后是'f_0',它们是唯一不同的,从而触发你想要的效果。

    entry 单独作为键也不起作用,因为它已经存在于 DOM 中,所以它不会重新渲染过渡。

    <Transition
      native
      from={{
        transform: `translateY(${index === 0 ? "-200%" : "-100%"})`
      }}
      to={{ transform: "translateY(0)" }}
      config={config.slow}
      key={`${entry}_${index}`}
    >
    

    在这里查看https://codesandbox.io/s/kkp98ry4mo

    【讨论】:

    • 非常感谢,现在我更了解react-spring 的工作原理了!
    • 没问题@3Dos,“复合键”没有很好的文档记录。有时键需要唯一的值,然后需要一个属性来按顺序进行更改/速度。
    猜你喜欢
    • 2021-07-03
    • 2021-10-04
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2021-08-12
    • 2017-04-02
    • 2020-01-11
    • 2022-10-08
    相关资源
    最近更新 更多