我正在尝试为一张卡的进出设置动画。如果有选定的值,则会显示卡片。如果所选项目未定义,则卡片将消失。我得到了这个工作。
我尝试做的下一件事是,如果选择发生了变化(一个新项目(,则制作一张卡片的动画,并制作一张新卡片的动画。我不知道该怎么做。。。以下是我尝试过的那种作品。
很明显,我不明白该怎么做。我想知道我是否需要把它分成两张卡并运行useChain。
const App: React.FC = () => {
//...
const [selectedItem, setSelectedItem] = useState<TimelineItem | undefined>(undefined);
const [lastSelectedItem, setLastSelectedItem] = useState<TimelineItem>({
content: '',
start: new Date(),
id: 0,
});
//...
const transitions = useTransition(
[selectedItem, lastSelectedItem],
item => (item ? item.id : 0),
{
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 },
}
);
return (
<Timeline
onItemSelect={item => {
if (selectedItem) setLastSelectedItem(selectedItem);
setSelectedItem(item);
}}
/>
{transitions.map(({ item, key, props }) => {
return (
item && (
<animated.div style={props}>
{item === selectedItem ? (
<ItemDetails
item={selectedItem} // If the selected item is undefined, this will not be running (happens when unselecting something)
groups={groups}
key={key || undefined} // key becomes undefined since item is
></ItemDetails>
) : (
false && ( // The last item never shows, it still has the data for the lastSelectedItem (For the fade out while the new Item is being shown or there is no new item).
<ItemDetails
item={lastSelectedItem}
groups={groups}
key={key || undefined}
></ItemDetails>
)
)}
</animated.div>
)
);
})}
);
};
如果我很了解您,您希望显示数组的状态。新元素逐渐消失,旧元素逐渐消失。这是Transition创建的功能。我认为它可以做得简单得多。我会更改状态管理并处理状态中的数组。而且渲染应该简单得多。
UPDATE:当进入元素的动画等待离开元素的动画完成时,我创建了一个示例。我用插值法做的。o值从0变为1表示回车,从1变为2表示离开。所以不透明度会改变:
离开:1->0->0
输入:0->0->1
这是代码:
import React, { useState, useEffect } from "react";
import { useTransition, animated } from "react-spring";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [cards, set] = useState(["A"]);
useEffect(() => {
setInterval(() => {
set(cards => (cards[0] === "A" ? "B" : "A"));
}, 4000);
}, []);
const transitions = useTransition(cards, null, {
from: { o: 0 },
enter: { o: 1 },
leave: { o: 2 },
config: { duration: 2000 }
});
return transitions.map(({ item, key, props }) => (
<div style={{ fontSize: "300px" }}>
<animated.div
style={{
position: "absolute",
opacity: props.o.interpolate([0, 0.5, 1, 1.5, 2], [0, 0, 1, 0, 0])
}}
>
{item}
</animated.div>
</div>
));
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
工作示例:https://codesandbox.io/s/react-spring-staggered-transition-xs9wy