当使用react-spring
v9.x中的新useTransition
挂钩更改进行筛选时,我正在尝试为列表的转换设置动画,以便在筛选列表项时,其余项移动到它们的新位置。
到目前为止,我已经设法让列表中的组件淡入和淡出,但一旦淡出动画完成,剩下的组件就会立即跳到它们的新位置。我无法改变这一点。
如何设置剩余组件的动画以平滑地移动到它们的新位置?
这是当前代码的代码沙箱链接。
如果您在搜索栏中键入"p",并观看名称为Plum
的组件在短时间延迟后跳起来,您可以最清楚地看到跳跃效果。
App.js
import { useState } from "react";
import { useSpring, useTransition, animated } from "react-spring";
export default function App() {
const [items, setItems] = useState([
{ name: "Apple", key: 1 },
{ name: "Banana", key: 2 },
{ name: "Orange", key: 3 },
{ name: "Kiwifruit", key: 4 },
{ name: "Plum", key: 5 }
]);
const [searchText, setSearchText] = useState("");
const filteredItems = items.filter((item) =>
item.name.toLowerCase().includes(searchText.toLowerCase())
);
const transition = useTransition(filteredItems, {
from: { opacity: 0 },
enter: { opacity: 1 },
leave: { opacity: 0 }
});
const fadeInListItems = transition((style, item) => {
return (
<animated.div style={style}>
<Item data={item} />
</animated.div>
);
});
const handleSearchBarChange = ({ target }) => setSearchText(target.value);
return (
<div className="App">
<h2>Click on an item to toggle the border colour.</h2>
<SearchBar onChange={handleSearchBarChange} value={searchText} />
{fadeInListItems}
</div>
);
}
const SearchBar = (props) => {
return (
<>
<label>Search Bar: </label>
<input onChange={props.onChange} value={props.searchText} type="text" />
</>
);
};
const Item = (props) => {
const [isClicked, setIsClicked] = useState(false);
const [styles, api] = useSpring(() => ({
border: "2px solid black",
margin: "5px",
borderRadius: "25px",
boxShadow: "2px 2px black",
backgroundColor: "white",
color: "black"
}));
const handleClick = (e) => {
api.start({
backgroundColor: isClicked ? "white" : "red",
color: isClicked ? "black" : "white"
});
setIsClicked((prev) => !prev);
};
return (
<animated.div style={styles} onClick={handleClick} key={props.data.key}>
{props.data.name}
</animated.div>
);
};
您可以通过使用max-height
隐藏过滤后的元素(以及渐变(来实现此效果。以这种方式;塌陷";而不仅仅是褪色,这样剩下的元素就会"消失";幻灯片";向上的
瞬态
const transition = useTransition(filteredItems, {
from: { opacity: 0, marginTop: 5 },
enter: { opacity: 1, maxHeight: 50, marginTop: 5 },
leave: { opacity: 0, maxHeight: 0, marginTop: 0 }
});
我还添加了overflow: hidden
以完成maxHeight
的效果,并删除了Item
的margin: 5px
,因为我在转换-定义中添加了裕度。
const [styles, api] = useSpring(() => ({
border: "2px solid black",
-- margin: "5px",
borderRadius: "25px",
boxShadow: "2px 2px black",
backgroundColor: "white",
color: "black",
++ overflow: "hidden",
}));
https://codesandbox.io/s/react-spring-demo-change-border-colour-on-click-forked-7fdkl