代码之家  ›  专栏  ›  技术社区  ›  3Dos

React spring动画仅在第一次渲染时有效

  •  1
  • 3Dos  · 技术社区  · 6 年前

    我尝试在数组中设置新条目的动画 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 同样的结果。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Rodney Hawkins    6 年前

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

    当把钥匙换成 ${entry}_${index} ,它会将它们的密钥更新为'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