【发布时间】:2020-07-18 19:51:15
【问题描述】:
我正在努力理解 React Spring。所以我有一些盒子,我需要通过活动索引过滤它们,想法是动画盒子渲染,但我只有在组件第一次渲染时才有动画。
这是我目前所拥有的:
import React from "react";
import ReactDOM from "react-dom";
import styled from "@emotion/styled";
import { useTransition, animated } from "react-spring";
import "./styles.css";
const Header = styled.div`
display: flex;
justify-content: center;
margin-bottom: 16px;
`;
const Content = styled.div`
display: flex;
justify-content: center;
`;
const Box = styled.div`
width: 64px;
height: 64px;
background-color: yellow;
border: 3px solid yellowgreen;
color: yellowgreen;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
`;
const EnhancedBox = animated(Box);
const App = () => {
const [activeBoxIndex, setActiveBoxIndex] = React.useState(0);
const boxes = [
{ label: "1", key: 0 },
{ label: "2", key: 1 },
{ label: "3", key: 2 }
];
const transition = useTransition(boxes, item => item.key, {
from: { maxHeight: "0px", overflow: "hidden", margin: "0px 0px" },
enter: { maxHeight: "100px", overflow: "hidden", margin: "5px 0px" },
leave: { maxHeight: "0px", overflow: "hidden", margin: "0px 0px" }
});
const handleBoxClick = n => () => {
setActiveBoxIndex(n);
};
return (
<div className="App">
<Header>
<button onClick={handleBoxClick(0)}>Show box 1</button>
<button onClick={handleBoxClick(1)}>Show box 2</button>
<button onClick={handleBoxClick(2)}>Show box 3</button>
</Header>
<Content>
{transition.map(({ item, props, key }) => {
return item.key === activeBoxIndex ? (
<EnhancedBox key={item.key} style={props}>
{item.label}
</EnhancedBox>
) : (
<></>
);
})}
</Content>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
我设置了一个代码沙盒项目以使事情变得更容易。任何帮助将非常感激。 https://codesandbox.io/s/wizardly-hill-6hkk9
【问题讨论】:
-
我一直在处理这样的问题。您的动画都在同时渲染,因为您正在为整个 box 数组设置动画。您需要做的是在按钮单击时操作数组
标签: javascript css animation react-spring