React-spring动画仅在第一次渲染时有效 [英] React-spring animation only works at first render
问题描述
我尝试为数组中的新条目设置动画,因为它们以react-spring
出现.在第一次渲染时效果很好,但是在更新时却不动画
I try to animate new entries in an array as they appear with react-spring
It works quite fine at the first render but then doesn't animate when updated
这是一个代码沙箱,我在其中以一定间隔重现了该问题: https://codesandbox.io/s/01672okvpl
Here's a code sandbox where I reproduced the issue with an interval : 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
获得相同的结果.
I tried with Spring
and Transition
with the same result.
推荐答案
您的问题是因为您的密钥未更新.由于您将0的键替换为0的键,因此它认为它已经应用了过渡.
Your problem is because your Key is not updating. Since you are replacing key of 0 with key of 0, it think it has already applied the transition.
将关键点更改为${entry}_${index}
时,它将把它们的关键点更新为"a_0",然后更新为"f_0",这是唯一且不同的,因此会触发您想要的效果.
When changing the key to be ${entry}_${index}
, it'll update they key to 'a_0', then 'f_0' which are unique and different, and therefore trigger the effect you want.
entry
作为密钥也不起作用,因为它已经存在于DOM中,因此不会重新呈现过渡.
entry
alone as a key does not work either, since it already exists in the DOM, so it'll not re-render the transition.
<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动画仅在第一次渲染时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!